PHP array() function

PHP array() function

The array() function in PHP is used to create an array.

Syntax

array ([ mixed $... ] )

Parameter

…(optional)- This parameter represents the elements’ values along with keys of the array. The syntax of this is as follows:

"index => values" where the index represents a type string or integer. The possible index values are given below,

  • If the index is omitted, an integer index is automatically generated, starting from 0 and incremented with +1.
  • If the index is an integer, the next generated index will be the biggest integer index + 1
  • If there are two identical indexes, the last index overwrites the first.

Return

This parameter returns an array of the parameters.

Example 1

 values" 
 $array = array(1=>"A", 2=>"B", 3=>"C", 4=>"D", 5=>"E", 6=>"F");
 //printing the array
 print_r($array);
 ?> 

Output

Array
 (
     [1] => A
     [2] => B
     [3] => C
     [4] => D
     [5] => E
     [6] => F
 ) 

Example 2

 values" 
 //If the index is not passed, an integer index is automatically generated, starting from 0
 $array = array("A", "B", "C", "D", "E", "F");
 //printing the array
 print_r($array);
 ?> 

Output

Array
 (
     [0] => A
     [1] => B
     [2] => C
     [3] => D
     [4] => E
     [5] => F
 ) 

Example 3

 array(1 => "mango", 2 => "banana", 2 => "apple"),
     "numbers" => array(1, 2, 3, 4, 5, 6),
     "values"   => array("first", 5 => "second", "third")
 );
 //printing the array 
 print_r($array);
 ?> 

Output

Array
 (
     [fruits] => Array
         (
             [1] => mango
             [2] => apple
         )
     [numbers] => Array 
         (
             [0] => 1
             [1] => 2
             [2] => 3
             [3] => 4
             [4] => 5
             [5] => 6
         )
     [values] => Array
         (
             [0] => first
             [5] => second
             [6] => third
         )
 ) 

Example 4

 'Reema','');
 //Accessing the array inside double quotes
 echo "Hello {$array['Name']}!"; // will return Hello Reema!
 ?> 

Output

Hello Reema!