Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php in_array() or array_search() not working [duplicate]

Tags:

arrays

php

I am using a simple php script to look for an element in an array like

    $restricted = array('root/base', 'root2' ); 
    print_r($restricted);
    if( array_search('root/base', $restricted) ){
        echo "1";
    } else {
        echo "0";
    }

But I am always getting the following output

Array ( [0] => root/base [1] => root2 ) 0

This means that the array_search is failing to find the element in the given array. Can anybody show some light on whats happening?

I tried to replace array_search() with in_array() also. But that too returned the same error.

like image 588
rahul Ram Avatar asked May 25 '13 14:05

rahul Ram


People also ask

What is the difference between in_array and Array_search?

The main difference between both the functions is that array_search() usually returns either key or index whereas in_array() returns TRUE or FALSE according to match found in search. Value: It specifies the value that needs to be searched in an array.

What is the use of in_array () function?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Is in_array slow?

PHP's in_array() function is really slow.

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.


1 Answers

From PHP DOC

array_search — Searches the array for a given value and returns the corresponding key if successful

The index is 0 that is why you think its fails

Use

array_search('root/base', $restricted) !== false
like image 110
Baba Avatar answered Nov 03 '22 01:11

Baba