An array is a data structure set of elements that store multiple values in a single variable on the pair basis of key/value
An array is a compound types data type, it is hold more than one value at a time
$name1 ='Vishal Gupta'; $name2 ='Vipin Katiyar'; $name3 ='Harshendra';
Supposed you have 1000 names then it is not good solution to create 1000 variables, we have to create an array
$name =array('name1'=>'Vishal Gupta','name2'=>'Vipin Katiyar','name3' =>'Harshendra');
echo $name['name1'];
//output : Vishal Gupta
array() function to used create an array
array();
There are three types of arrays in PHP. These are:
In Indexed array each elements with a numric key
//Indexed array syntax
//Indexed assigned automatically
$lang = array('PHP','Java','C#');
or:
//Indexed assigned manually $lang[0]='PHP'; $lang[1]='Java'; $lang[2]='C#';
Associative arrays is like indexed array, but Index can be of any data type. data stored at key,value pair.
//Associative array syntax
$user_qualification = array("Vishal"=>'MCA','Vipin'=>'B.tech','Harsh'=>'MBA');
or:
$user_qualification['Vishal']='MCA'; $user_qualification['Vipin']='B.tech'; $user_qualification['Harsh']='MBA';
In Multidimensional array is an array of arrays, in which each element can be also an array. Example : 2D,3D (an array of arrays of arrays.), etc
//Multidimensional array syntax
$users = array(
array('name'=>'Pradeep','email'=>'abc@example.com'),
array('name'=>'Rahul','email'=>'xyd@example.com')
);
echo $users[0]['name'];
//Output :: Pradeep
You get the length of the array by using count()
$users = array(
array('name'=>'Pradeep','email'=>'abc@example.com'),
array('name'=>'Rahul','email'=>'xyd@example.com')
);
echo count($users); //2
echo count($users,1); //6
By using print_r() or var_dump() view the array elements.
$users = array(
array('name'=>'Pradeep','email'=>'abc@example.com'),
array('name'=>'Rahul','email'=>'xyd@example.com')
);
Array ( [0] => Array ( [name] => Pradeep [email] => abc@example.com ) [1] => Array ( [name] => Rahul [email] => xyd@example.com ) )
array (size=2)
  0 => 
    array (size=2)
      'name' => string 'Pradeep' (length=7)
      'email' => string 'abc@example.com' (length=15)
  1 => 
    array (size=2)
      'name' => string 'Rahul' (length=5)
      'email' => string 'xyd@example.com' (length=15)