18

I have this code

$restaurant = array('/restaurant_pos/', '/bar_nightclub_pos/')
$current_page = $_SERVER['REQUEST_URI'];

if (array_search($current_page, $restaurant)) {
    echo "KEEP ME";
}

the problem is the array_search is returning 0 because '/restaurant_pos/' is the first element in the array which is causing the if to fail...any ideas on how to check if the value is in the array without failing on the first element

0

4 Answers 4

44
if (array_search($current_page, $restaurant) !== FALSE ) {
    echo "KEEP ME";
}

Manual link: http://php.net/manual/en/function.array-search.php

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

4 Comments

+1: this is documented in the manual (I'll add the link to your answer) - in fact, they make a point of explaining it carefully - so OP clearly didn't research before asking.
Haha, never even saw that myself. Thanks about that!
thanks and i did look at the documentation and noticed the big red box but i tried !== false and it failed so i posted the question...thanks @Jan Westerdiep
Hey.. no worries. We all make those tiny mistakes (and then spend 20 minutes before having that "GOTCHA" feeling..!)
6

I think it will be better to use in_array() in this case

$restaurant = array('/restaurant_pos/', '/bar_nightclub_pos/')
$current_page = $_SERVER['REQUEST_URI'];

if (in_array($current_page, $restaurant)) {
    echo "KEEP ME";
}

http://php.net/manual/en/function.in-array.php

1 Comment

Still couldn't get the !== FALSE to work with array_search. This one worked for me. Thanks!
2

I have used is_numeric function to achieve the same.

if(is_numeric(array_search($entry, $array))){
            //if true, this block will be executed
 }

Comments

0

From my own experience, if you got, for example:

Array
(
    [1] => Array
        (
            [0] => a
            [1] => b
        )

    [2] => Array
        (
            [0] => b
        )
    [4] => Array
        (   
           [0] => c
        )
)

On array_search("a", $array[3]) !== FALSE) it returns TRUE the same, so to cover all cases, also on null element, it's better use:

if ( (array_search($element, $array) !== FALSE) && ($array) ) {
    echo "found";
}

Hope it helps.

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.