PHP Array with Code Examples

In PHP, an array is a data structure that can hold multiple values. Arrays are indexed, which means that each value in the array has a unique identifier. Arrays can be used to store a variety of data types, including strings, numbers, objects, and even other arrays.


There are three types of arrays in PHP:


Indexed arrays: Indexed arrays are the most common type of array. They are indexed by numbers, starting from 0.

Associative arrays: Associative arrays are indexed by strings. This means that you can use any string as the index of an element in the array.

Multidimensional arrays: Multidimensional arrays are arrays that contain other arrays. This allows you to store data in a nested fashion.

To create an array in PHP, you can use the array() function. The array() function takes a list of values as its argument. The values can be of any type, and they can be separated by commas.


For example, the following code creates an indexed array with three elements:

$array = array(1, 2, 3);


The following code creates an associative array with two elements:

$array = array('name' => 'John Doe', 'age' => 30);


The following code creates a multidimensional array with two arrays:

$array = array(array(1, 2, 3), array(4, 5, 6));


Once you have created an array, you can access its elements using the index. For example, the following code prints the value of the first element in the array $array:

echo $array[0];


You can also use the foreach loop to iterate over the elements in an array. The foreach loop will automatically increment the index for you, so you don't need to worry about it.


For example, the following code prints the values of all the elements in the array $array:

foreach ($array as $value) {

    echo $value;

}


Arrays are a powerful data structure that can be used to store a variety of data. They are easy to use and can be manipulated in a variety of ways.

No comments:

Post a Comment