Tags
Asked 3 years ago
9 Jun 2021
Views 250
steave

steave posted

how to get values in php multidimensional array ?

how to get values in php multidimensional array ?
jqueryLearner

jqueryLearner
answered Apr 26 '23 00:00

To get values from a multidimensional array in PHP, you can use nested loops or array functions such as array_walk_recursive() or array_column(). Here are some examples:

Example 1: Using nested loops




$multiArray = array(
    array("id" => 1, "name" => "John"),
    array("id" => 2, "name" => "Mary"),
    array("id" => 3, "name" => "Bob")
);


foreach ($multiArray as $innerArray) {
    foreach ($innerArray as $key => $value) {
        echo "$key: $value<br>";
    }
}

Output:



id: 1
name: John
id: 2
name: Mary
id: 3
name: Bob

Example 2: Using array_walk_recursive()



$multiArray = array(
    array("id" => 1, "name" => "John"),
    array("id" => 2, "name" => "Mary"),
    array("id" => 3, "name" => "Bob")
);

function printValues($value, $key) {
    echo "$key: $value<br>";
}


array_walk_recursive($multiArray, 'printValues');
Output:



id: 1
name: John
id: 2
name: Mary
id: 3
name: Bob

Example 3: Using array_column()



$multiArray = array(
    array("id" => 1, "name" => "John"),
    array("id" => 2, "name" => "Mary"),
    array("id" => 3, "name" => "Bob")
);

$names = array_column($multiArray, 'name');
print_r($names);

Output:



Array
(
    [0] => John
    [1] => Mary
    [2] => Bob
)

These are just a few examples of how to access values in multidimensional arrays in PHP. The specific approach you choose will depend on the structure and contents of your array, as well as the task you are trying to accomplish.
Post Answer