Friday, September 6, 2019

Array In PHP

Array In PHP

In PHP basic, we are using variables to store any data and display on web.

$student1 = 'Suresh Kumar';
$student2 = 'Sarita Khanna';
$student3 = 'Mohan Sinha';
$student4 = 'Kamlesh';

But sometime, we want to store same type data more than one time like we want to store student names of a group or to store name of cricket players. In this case, we use Array means Array is use to store a group of data is a single variable.

$student[0] = 'Suresh Kumar';
$student[1] = 'Sarita Khanna';
$student[2] = 'Mohan Sinha';
$student[3] = 'Kamlesh';

In above example, we used [0], [1], [2], [3] called index. In Array, index starts with 0(zero).
There are three types array in PHP.
1. Indexed Array Or Numeric Array
2. Associative Array
3. Multidimensional Array

Indexed Array Or Numeric Array
In this type array, each element stores with numeric index(0, 1, 2, 3...).
$student[0] = 'Suresh Kumar';
$student[1] = 'Sarita Khanna';
$student[2] = 'Mohan Sinha';
$student[3] = 'Kamlesh';

The above example is same as below.
$student = array('Suresh Kumar', 'Sarita Khanna', 'Mohan Sinha', 'Kamlesh');
After print, it will display:

    [0] => Suresh Kumar
    [1] => Sarita Khanna
    [2] => Mohan Sinha
    [3] => Kamlesh

For display, you can use print_r($student);

Associative Array
In this type array, we use data in key and value format. Suppose, we want to make array for student names and his age, then we can use associative array. For example:

$student = array('Suresh Kumar'=>22, 'Sarita Khanna'=>24, 'Mohan Sinha'=>20, 'Kamlesh'=>26);

For display above array, you can use foreach.
foreach($student AS $studentName => $age){
echo 'Age of '.$studentName.' is '.$age.'.'.'<br/>';

Here  $studentName represent to key and $age represent to value.

$student['Suresh Kumar'] = 22;
$student['Sarita Khanna'] = 24;
$student['Mohan Sinha'] = 20;
$student['Kamlesh'] = 26;

Multidimensional Array
In this type array, we use one or more level to display data. Suppose, we want to store student name with his age and total obtained marks.
$studentData = array('Suresh Kumar'=>array(22, 550), 'Sarita Khanna'=>array(24, 650), 'Mohan Sinha'=>array(20, 570), 'Kamlesh'=>array(26, 620));

For display above array,

foreach($studentData AS $stName => $stData){
echo 'Age of '.$stName.' is '.$stData[0].'. He obtained '.$stData[1].' marks.'.'<br/>';

If you have any question, please write us at

No comments:

Post a Comment

Copyright © 2019 Tech Location BD. All Right Reserved