PHP Arrays

PHP Arrays

PHP Arrays

In PHP, an array is a variable that can hold multiple values. Arrays can be indexed numerically or by a string, and can hold values of different data types.

Here’s an example of creating an indexed array in PHP:

				
					$fruits = array("apple", "banana", "cherry", "date");
				
			

In this example, we create an array called $fruits that contains four elements, indexed from 0 to 3.

 

Here’s an example of creating an associative array in PHP:

				
					$person = array(
    "name" => "John",
    "age" => 30,
    "email" => "john@example.com"
);

				
			

In this example, we create an array called $person that has three elements, indexed by strings.

 

We can access array elements using their index or key, like this:

				
					echo $fruits[1]; // Outputs "banana"
echo $person["name"]; // Outputs "John" 

				
			

We can also use loops to iterate over the elements in an array:

				
					foreach ($fruits as $fruit) {
    echo $fruit . " ";
}

// Outputs: apple banana cherry date 

				
			

PHP provides a variety of built-in functions for working with arrays, such as count(), sort(), array_push(), array_pop(), array_shift(), array_unshift(), array_merge(), array_intersect(), and array_diff().

Join To Get Our Newsletter
Spread the love