How can I do simple check in the following scenario. This is my array:
[data] => Array ( [0] => blog ... )
This does not seem to be working:
if(isset($data[1]) != "page") {
do stuff here...
}
I need to check if key [1] is set and value not equal to "page"
I found a better solution:
if(!array_search("page", $data)) {
// do stuff here
}
This works for me
if(isset($data) && isset($data[1]) && $data[1] != 'page') {
// do something
}
You may be thinking, "why isn't he checking if $data
is an array?" Because it doesn't matter you can access strings from subscripts in PHP.
Isset only returns booleans so you cannot compare the result to the string 'page' you will need to make 2 separate checks.
Also i am not sure if you wanted to check if the first element had page or that the element at index 1 had page (php arrays start at 0 if you don't define).
But it should be at least something like if(isset(data[1]) && data[1] != 'page')
You are doing it wrong because isset
will return bool not the value of $data[1]
.
Anyways, you can try the approach below:
if(isset($data) && array_key_exists(1, $data) && $data[1] != "page")
do stuff here...
}
array_key_exist
will return true if key 1
exists in $data
array and then will compare the data[1]
with string.