开发者

Search for variable in array()

If I had this code:

$result = 1;

$square = array(

"00" => -1,
"0" => 0,
"1" => 1,

);

And wanted to know whether $result is equal to ANY of the array VALUES of $square (-1, 0 or 1).

I´m am guessing there should be a function that compares a variable to all the array´s values and returs TRUE or FALSE accordingly.

If there isn´t such a function I am open to any suggestions and/or workarounds you might have hidden under your sleeves :)

Thanks in 开发者_开发问答advance


You're looking for in_array():

$result = 1;
$square = array( "00" => -1, "0" => 0, "1" => 1, );

if (in_array($result, $square)) {
    echo "Found something!";
}


in_array should work for you.

if(in_array($result, $square)) {
   //$result is in there.
}


If your array is going to be large (>500 elements), you're going to want to do this:

$flip_square = array_flip($square);
return isset($flip_square["string_to_search_for"]);

If you don't do this, it can be deathly slow. This is many times faster than in_array().


if(array_search($result,$square)===false) { echo "DNE"; }

Note the ===!

EDIT: switched function parameters - sorry


There is a function in php that will do this. It is known as array_search(); For your code above you would use

if(false !== array_search($square, $result)){
echo "Found something";
}

The link to the documentation can be found here. Look towards the bottom for code examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜