tags:

views:

286

answers:

5

How can I check this:

$something = array('say' => 'bla', 'say' => 'omg');

How can I check if the $something['say'] has the value of 'bla' or 'omg'

Best Regards,

+3  A: 

Using if?

if(isset($something['say']) && $something['say'] == 'bla') {
    // do something
}

Btw, you are assigning an value with the key say twice, hence your array will result in an array with only one value.

Tatu Ulmanen
A: 

You could use the PHP in_array function

if (in_array("bla", $something)) {
    echo "has bla";
}

Note: You should not have an associative array with two keys that are the same.

Benjamin Ortuzar
+1  A: 

To check if the index is defined: isset($something['say'])

echo
A: 

Well, first off an associative array can only have a key defined once, so this array would never exist. Otherwise, just use in_array() to determine if that specific array element is in an array of possible solutions.

animuson
A: 

You can test whether an array has a certain element at all or not with isset() or sometimes even better array_key_exists() (the documentation explains the differences). If you can't be sure if the array has an element with the index 'say' you should test that first or you might get 'warning: undefined index....' messages.

As for the test whether the element's value is equal to a string you can use == or (again sometimes better) the identity operator === which doesn't allow type juggling.

if( isset($something['say']) && 'bla'===$something['say'] ) {
  // ...
}
VolkerK