开发者

in_array for a combo value ('test','value')

I'm trying to use in_array or something like it for associative or more complex arrays.

This is the normal in_array

in_array('test', array('test', 'exists')); //true
in_array('test', array('not', 'exists')); // false

What I'm trying to search is a pair, like the combination 'test' and 'value'. I can set up the combo to be searched to array('test','va开发者_JAVA百科lue') or 'test'=>'value' as needed. But how can I do this search if the array to be searched is

array('test'=>'value', 'exists'=>'here');
or
array( array('test','value'), array('exists'=>'here') );


if (
    array_key_exists('test', $array) && $array['test'] == 'value' // Has test => value
    ||
    in_array(array('test', 'value'), $array) // Has [test, value]
) {
    // Found
}


If you want to see if there is a key "test" with a value of "value" then try this:

<?php
$arr = array('key' => 'value', 'key2' => 'value');
if(array_key_exists('key',$arr) && $arr['key'] == 'value'))
     echo "It is there!";
else
     echo "It isn't there!";
?>


If I understand you correctly, you're looking for a function called array_search()

It accepts a mixed value, so you can even search for objects - I haven't tried it exactly, but it should work for your use case:

if (array_search(array('test','value'), array(array('test','value'),array('nottest','notvalue'))) !== false) {
    // item found...
}

ok..

However I think you'll find this method the most useful:

If you just need to find out if a certain key/value pair is located in an array, the easiest way to do it is like this:

<?php
if (isset($arr['key']) && $arr['key'] == 'value') { 
    // we have a match...
}
?>

if you need to find something in a more complex pattern, there's no avoid creating a bigger loop.


Separate Keys from Values and use in_array()

$myArray = array('test'=>'value', 'exists'=>'here');
array_keys($myArray)
array_values($myArray)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜