PHP Access Arrays
In PHP, arrays are ordered collections of items that can hold various data types, including integers, strings, floats, booleans, and even other arrays. Accessing elements within an array involves specifying their index, which is a numeric position starting from 0.
Example
Access an item by referring to its index number:
<!DOCTYPE html> <html> <body> <?php $cars = array("Volvo", "BMW", "Toyota"); echo $cars[2]; ?> </body> </html>
Output
Toyota
• Double or Single Quotes
You can use both double and single quotes when accessing an array:
Example
<!DOCTYPE html> <html> <body> <?php $cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); echo $cars["model"]; echo "
"; echo $cars['model']; ?> </body> </html>
Output
Mustang
Mustang
• Excecute a Function Item
In PHP, "executing a function" simply means running the code defined within the function's body.
To execute such a function, use the index number followed by parentheses ():
Example
Execute a function item:
<!DOCTYPE html> <html> <body> <?php function myFunction() { echo "I come from a function!"; } $myArr = array("Volvo", 15, myFunction); $myArr[2](); ?> </body> </html>
Output
I come from a function!
• Loop Through an Associative Array
In PHP, looping through an associative array allows you to iterate over its key-value pairs, accessing both the keys (names) and the values (data) associated with them.
Example
Display all array items, keys and values:
<!DOCTYPE html> <html> <body> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); foreach ($car as $x => $y) { echo "$x: $y
"; } ?> </body> </html>
Output
brand: Ford
model: Mustang
year: 1964