1

How do I know if a key in an array is true? If not, then don't use this

[0] => array
(
[id] => 1
[some_key] => something
)

[1] => array
(
[id] => 2
)

[2] => array
(
[id] => 3
[some_key] => something
)

foreach($array as $value){
$id = $value->id;
if($value->some_key === TRUE){
$some_key = $value->some_key; //some may have this key, some may not
}
}

Not sure what is the proper statement to check if this array has that some_key. If I don't have a check, it will output an error message.

Thanks in advance.

1
  • Is it the keys you want to check for or the value? Because you keep saying keys, but your checking for a value. Commented Mar 11, 2012 at 9:07

4 Answers 4

2

Try

isset($array[$some_key])

It will return true if the array $array has an index $some_key, which can be a string or an integer.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the isset() function to see if a variable is set.

foreach($array as $value){
    $id = $value->id;
    if(isset($value->some_key)){
        $some_key = $value->some_key;
    }
}

Comments

1

Others have mentioned isset(), which mostly works. It will fail if the value under the key is null, however:

$test = array('sampleKey' => null);
isset($test['sampleKey']); // returns false

If this case is important for you to test, there's an explicit array_key_exists() function which handles it correctly:

http://php.net/manual/en/function.array-key-exists.php

1 Comment

Good point. However, it's worth noting that this won't work on objects. For objects you need to use the property_exists() function: php.net/manual/en/function.property-exists.php
1
function validate($array)
{
    foreach($array as $val) {
        if( !array_key_exists('id', $val) ) return false;
        if( !array_key_exists('some_key', $val) ) return false;
    }
    return true;
}

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.