Accessing Arrays

Accessing Array Items: Getting the Data Out

Once you've created an array, you need to access the values inside. The syntax depends on whether you're working with indexed or associative arrays.

Indexed arrays use numbers:

For indexed arrays, you access items by their position number in square brackets. Remember that PHP starts counting at 0, so the first item is $cars[0], the second is $cars[1], and so on. If you have three items, the last one is at index 2, not 3.

Associative arrays use key names:

For associative arrays, you use the key name in square brackets: $car["brand"] or $car["model"]. This is much more readable than trying to remember numeric positions.

Quotes don't matter (mostly):

You can use either double quotes or single quotes when accessing array keys: $car["model"] and $car['model'] both work identically. Pick one style and stay consistent — most developers prefer single quotes for simple strings because they're cleaner.

Arrays can store functions:

This is where things get interesting. Array items can be any data type, including functions. When you store a function in an array, you execute it by adding parentheses after the array access: $myArr[2]() or $myArr["message"](). The array holds a reference to the function, and the parentheses tell PHP to actually run it.

You won't use this often as a beginner, but it's powerful for advanced patterns like callback arrays and event systems that WordPress uses internally.

Looping remains your best tool:

Whether indexed or associative, foreach loops let you process every item without manually accessing each one. For associative arrays, use foreach ($array as $key => $value) to get both the key and value. For indexed arrays where you only care about values, use foreach ($array as $value).

Why This Matters:

Accessing array data correctly is how you extract information from WordPress functions. When you call get_user_meta() or get_post(), you get an array back. Knowing how to pull out the specific pieces you need — whether by index or key name — is essential for every support ticket you'll handle.