2

if i'm accessing an index like that

$var = $final_Length_Array[1][0]['id'];

how to check whether the "id" key index exist in the array or not.

i tried to use function array_key_exists but it seems to be working only on one dimension array.

i tried it like if(array_key_exists('id',$final_Length_Array)){ but it didn't work

i also tried isset to check whether there is a result or not but it didn't work also if(isset($final_Length_Array[1][0]['id'])){

any help i'll be appreciate it

5
  • Please give an example array that gives you the problem. Commented Nov 3, 2017 at 23:16
  • the array is like [ { "name": "John Doe", "year": "1st", "curriculum": "Arts" } ] Commented Nov 3, 2017 at 23:33
  • Then you don't have [1]. Commented Nov 3, 2017 at 23:33
  • actually the complete array is "list", [ { "name": "John Doe", "year": "1st", "curriculum": "Arts" } ] so "1" means the first array in list Commented Nov 3, 2017 at 23:38
  • With that data you last attempt (with isset) works. I cannot reproduce your problem. Commented Nov 3, 2017 at 23:39

2 Answers 2

5

Super hacky solution:

function array_key_exists_recursive($array, $key) {
    return strpos(json_encode($array), "\"" . $key . "\":") !== false;
}

Better solution:

$array = ['a' => ['b' => 'c']];
function array_key_exists_recursive($key, $array) {
    if (array_key_exists($key, $array)) {
        return true;
    }
    foreach($array as $k => $value) {
        if (is_array($value) && array_key_exists_recursive($key, $value)) {
            return true;
        }
    }
    return false;            
}

var_dump(array_key_exists_recursive('b', $array));
Sign up to request clarification or add additional context in comments.

Comments

0
$var = $final_Length_Array[1][0]['id'] ?? false;

returns the value of id or false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.