PHP Arrays

What Is an Array?

An array in PHP is a variable that can hold multiple values at once. Each value is associated with a key (either numeric or named).

Use arrays when you want to group related data.

Indexed Arrays

Indexed arrays use numeric keys (starting from 0):

Loading...
Output:

You can also use the short array syntax:

Loading...
Output:

Associative Arrays

Associative arrays use named keys instead of numeric indices:

Loading...
Output:

You can also assign values manually:

Loading...
Output:

Multidimensional Arrays

Arrays inside arrays (2D or more):

Loading...
Output:

Array Functions

PHP provides many built-in functions to work with arrays:

  • count() – Count number of elements
  • array_push() – Add to the end
  • array_pop() – Remove from the end
  • array_shift() – Remove from the beginning
  • array_unshift() – Add to the beginning
  • sort() – Sort indexed arrays
  • asort() – Sort associative arrays by value
  • ksort() – Sort associative arrays by key
Loading...
Output:

Check If It’s an Array

Use is_array() to confirm:

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper into any topic