Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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','value') 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') );
like image 278
sami Avatar asked Nov 28 '25 03:11

sami


2 Answers

if (
    array_key_exists('test', $array) && $array['test'] == 'value' // Has test => value
    ||
    in_array(array('test', 'value'), $array) // Has [test, value]
) {
    // Found
}
like image 195
BoltClock Avatar answered Nov 29 '25 17:11

BoltClock


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!";
?>
like image 31
Jason Avatar answered Nov 29 '25 15:11

Jason