I have this Method in my class, which is working great, (kind-of). But for, whatever reason, it returns NULL. Althrough if I put a (print_r($keys)) in the function, it will print it.
The RETURN is not passing the values. Any thoughts?
function arrayKeyPath ($searchFor, $arr, $keys=array())
{
if(!empty($arr) && is_array($arr)) {
if(isset($arr[$searchFor])) {
return $keys;
}
foreach($arr as $pKey => $a) {
if(is_array($a)) {
$keys[] = $pKey;
arrayKeyPath($searchFor, $a, $keys);
}
}
}
}
$user['results'][0] = array (
'userId' => '1',
'firstName' => 'John',
'lastName' => 'Doe',
'options' =>
array (
'showNews' => 'on',
'newOptions' => array(
'option1'=> 1,
'option2'=> 2,
'option3'=> 3
),
'connectWithTimeFrame1' => '30',
'defaultMessageTemplate' => '12',
'connectWithTimeFrame' => 90,
),
);
$exists = arrayKeyPath('option1', $user['results'][0]);
var_dump($exists);
Online Run Version https://ideone.com/fnml1S
So what you are basically trying to do is searching for a key in a multidimensional array. If you just want to check if the key is there at all, consider the following code:
// shamelessly copied from http://codeaid.net/php/extract-all-keys-from-a-multidimensional-array
function array_keys_multi(array $array) {
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($value))
$keys = array_merge($keys, array_keys_multi($value));
}
return $keys;
}
// in your case:
// array("results", 0, "userId", "firstName", "lastName", "options", "showNews", "newOptions", "option1", "option2", "option3", "connectWithTimeFrame1", "defaultMessageTemplate", "connectWithTimeFrame");
// call the function
$keys = array_keys_multi($user);
// check if the "option1" can be found in the array
if (in_array("option1", $keys))
echo "Yup, in there.";