1

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"

4 Answers 4

2
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.

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

5 Comments

Is it necessary to check if the array is set first? It's safe to just check the existence of the index.
I am checking if the variable exists in scope with isset($data). there is no need to check if it is an array, but you can if you prefer. It won't throw an error.
I'm saying there's no need to check if the variable exists.
No. If you try check if a subscript exists in a variable that does not exist, you will get a warning. You always have to check if a variable exists before trying to get values from it.
Are you sure? I thought that isset would discover that the array was undefined and return false at that point.
0

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')

Comments

0

I found a better solution:

if(!array_search("page", $data)) {
   // do stuff here
}

This works for me

Comments

0

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.

1 Comment

You will see Notice: Undefined variable: data if data is not set.

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.