PHP Create Arrays

In PHP, you can create arrays in several ways depending on the type of array you need: indexed, associative, or multidimensional.

1. Indexed Arrays

These arrays use numeric indexes starting from 0.

$fruits = array("Apple", "Banana", "Cherry");

Or using short syntax (PHP 5.4+):

$fruits = ["Apple", "Banana", "Cherry"];

2. Associative Arrays

These arrays use named keys that you assign to them.

$person = array( "first_name" => "John", "last_name" => "Doe", "age" => 30 );

Or with short syntax:

$person = [ "first_name" => "John", "last_name" => "Doe", "age" => 30 ];

3. Multidimensional Arrays

Arrays containing one or more arrays.

$users = [ ["name" => "Alice", "email" => "alice@example.com"], ["name" => "Bob", "email" => "bob@example.com"] ];

Tips:

  • Use print_r($array) or var_dump($array) to inspect arrays.

  • You can add values like this:

    $fruits[] = "Orange"; // adds to the end