Menu

What are Arrays in PHP?

  • Arrays are used to store multiple values under a common name.
  • An array is a special variable that can store multiple values.

Array Initialization in PHP

  • array() is used to create an empty array.
  • Suppose if you want to initialize a variable as an empty array, you can use it like this.
    $variable_name = array();
    //Where $variable_name is the name of the variable
    //Eg., $countries, $states, $colours etc.
  • Arrays in PHP can be divided into three,
    1. Indexed Arrays
    2. Associative Arrays
    3. Multidimensional Arrays

Indexed Arrays

  • Indexed arrays are the arrays in PHP with a numeric index.
  • Indexed arrays can be created by two methods.
    1. Assigned automatically
    2. Assigned manually

 Assigned Automatically

  • Syntax
    $array_name = array(value1,value2,...$valuen);
  • Example
    $colours = array("red","blue","green","yellow");

Associative arrays

  • Associative arrays are the arrays with named index.
  • There are two ways to create an associative array in PHP.

Assigned Automatically

  • Syntax
    $array_name = array(name1=>value1, name2=>value2,..... namen=>valuen);
  • Example
    $colours = array("colour1"=>"red", "colour2"=>"blue", "colour3"=>"green");

Assigned Manually

  • Syntax
    $array_name['name1'] = $value1;
    $array_name['name2'] = $value2;
    $array_name['name3'] = $value3;
    ...............
    $array_name['namen'] = $valuen;
  • Example
    $colours['colour1'] = "red"; $colours['colour2'] = "blue"; $colours['colour3'] = "green";

Multidimensional Arrays

  • A multidimensional array or Two dimensional (2D) array is an array of arrays.
  • We can store the data in the table in a multidimensional array.
    $vehicles = array(
     array('VehicleA',10,111),
     array('VehicleB',11,222)
     -----------------------
     -----------------------
    );