ÂÜÀòÂÒÂ×

Rydell Rollins

Human Resources Recruitment Coordinator at acKnowledge

Rydell Rollins has worked in a variety of roles in the Human Resources and Maintenance fields. Rydell began their career in 2013 as an HR/Store Manager at H&M. In 2018, they moved to the New York City Housing Authority (NYCHA) as a Maintenance Worker. In 2021, they were hired as a Human Resources Coordinator at HPL. Currently, they are employed as a Human Resources Recruitment Coordinator at akdm.

Q: How to make a function to get the value of a specific key in a multidimensional array

I have an array like this:

<code>$arr = array(

'a' =&gt; array(

'b' =&gt; array(

'c' =&gt; 'value'

)

)

);

</code>

I want to create a function to get the value of <code>c</code> key.

I have tried this:

<code>function get_value($arr, $key) {

foreach ($arr as $k =&gt; $v) {

if ($k == $key) {

return $v;

} elseif (is_array($v)) {

return get_value($v, $key);

}

}

return false;

}

echo get_value($arr, 'c');

</code>

But it doesn't work. How can I do this?

A:

You can use a recursive function to traverse the array.

<code>function get_value($arr, $key) {

foreach ($arr as $k =&gt; $v) {

if ($k == $key) {

return $v;

} elseif (is_array($v)) {

$result = get_value($v, $key);

if ($result !== false) {

return $result;

}

}

}

return false;

}

echo get_value($arr, 'c');

</code>

Links