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.
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;
}
}
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.
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:
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;
}