An array came as a PHP variable. It can store multiple values in a single array. It can be one dimensional or multidimensional too. You can use numeric value or and string as an index of the array.
Simple Array Example:
<?php
$array = array(
“fname” => “First name”,
“lname” => “Last name”,
);
?>
There are following types of Arrays:
- Indexed arrays – An array with numeric index or keys
- Associative arrays – An array with named or string index or keys
- Multidimensional arrays – An array contains one or more arrays.
Indexed arrays:
Here is an example of indexed array:
$name= array(‘A’,’B’,’C’);
Or
You can write it like:
$name[0]=’A’;
$name[1]=’B’;
$name[2]=’C’;
If you want to use any specific indexed value in your program then you can use the below example too:
Q: Create an array of names and print second name of array.
A: To do this you need to write the following:
<?php
//Creating an array
$name=array(‘Tim’,’Peter’,’John’,’Anna’);
echo $name[1];
//Here we used index 1 as array index starts from 0. This will return an output Peter.
?>
Associative arrays : Associative array is an array which used named key as index like
$student_name=array(‘fname’=>’Aarav’,’lname’=>’Maurya’);
Or you can assign values as follows:
$student_name[‘fname’]=’Aarav ’;
$student_name[’lname’]=’Maurya ’;
Multidimensional arrays: An array with one or more array called Multidimensional arrays. You can manage multiple level arrays in php but mostly more than 3 level will be hard to manage or keep remembering for programming.
Here is an example of students of class:
$students=array(
array(‘fname’=>‘Tom,’lname’=>Holland,’e_no’=>1,’marks’=>85),
array(‘fname’=>‘Aarav ’,’lname’=>’Maurya ’,’e_no’=>2,’marks’=>80),
);