PHP Access Arrays

Accessing arrays in PHP is straightforward. Here's a breakdown of how to work with different types of arrays in PHP:


1. Indexed Arrays

These are arrays with numeric keys, starting from 0 by default.

$colors = array("red", "green", "blue"); echo $colors[0]; // Outputs: red

2. Associative Arrays

These arrays use named keys that you assign to them.

$person = array("name" => "Alice", "age" => 30, "city" => "Paris"); echo $person["name"]; // Outputs: Alice

3. Multidimensional Arrays

Arrays containing one or more arrays.

$people = array( array("name" => "John", "age" => 25), array("name" => "Jane", "age" => 28) ); echo $people[1]["name"]; // Outputs: Jane

4. Accessing Elements Safely

To avoid errors when accessing keys that might not exist, use:

if (isset($person["name"])) { echo $person["name"]; }

Or with the null coalescing operator (PHP 7+):

echo $person["name"] ?? 'Unknown';