Tuesday 20 April 2021

Php: multi-dimensional arrays

Multidimensional arrays are actually arrays of arrays.

 

Example

$emp1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

$emp2 = [
    "id" => 2,
    "age" => 45,
    "name" => "Deeraj",
    "male" => true
];

$emps = [
    $emp1,
    $emp2
];

 

$emps variable is an array of employees. Find the below working application.

 

multi_dimension_array_demo.php

#!/usr/bin/php

<?php
$emp1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

$emp2 = [
    "id" => 2,
    "age" => 45,
    "name" => "Deeraj",
    "male" => true
];

$emps = [
    $emp1,
    $emp2
];

echo "Contents of arr1 are : \n";
foreach ($emps as $emp) {
    echo "Employee details: \n";
    foreach ($emp as $key => $value) {
        echo "$key => $value\n";
    }
    echo "\n\n";
}

?>

 

Output

$./multi_dimension_array_demo.php 

Contents of arr1 are : 
Employee details: 
id => 1
age => 32
name => Sailu
male => 


Employee details: 
id => 2
age => 45
name => Deeraj
male => 1

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment