How to check if an array value exists?
You could use the PHP in_array function
if( in_array( "bla" ,$yourarray ) )
{
echo "has bla";
}
Using: in_array()
$search_array = array('user_from','lucky_draw_id','prize_id');
if (in_array('prize_id', $search_array)) {
echo "The 'prize_id' element is in the array";
}
Here is output: The 'prize_id' element is in the array
Using: array_key_exists()
$search_array = array('user_from','lucky_draw_id','prize_id');
if (array_key_exists('prize_id', $search_array)) {
echo "The 'prize_id' element is in the array";
}
No output
In conclusion, array_key_exists()
does not work with a simple array. Its only to find whether an array key exist or not. Use in_array()
instead.
Here is more example:
<?php
/**++++++++++++++++++++++++++++++++++++++++++++++
* 1. example with assoc array using in_array
*
* IMPORTANT NOTE: in_array is case-sensitive
* in_array — Checks if a value exists in an array
*
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
*++++++++++++++++++++++++++++++++++++++++++++++
*/
$something = array('a' => 'bla', 'b' => 'omg');
if (in_array('omg', $something)) {
echo "|1| The 'omg' value found in the assoc array ||";
}
/**++++++++++++++++++++++++++++++++++++++++++++++
* 2. example with index array using in_array
*
* IMPORTANT NOTE: in_array is case-sensitive
* in_array — Checks if a value exists in an array
*
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
*++++++++++++++++++++++++++++++++++++++++++++++
*/
$something = array('bla', 'omg');
if (in_array('omg', $something)) {
echo "|2| The 'omg' value found in the index array ||";
}
/**++++++++++++++++++++++++++++++++++++++++++++++
* 3. trying with array_search
*
* array_search — Searches the array for a given value
* and returns the corresponding key if successful
*
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
*++++++++++++++++++++++++++++++++++++++++++++++
*/
$something = array('a' => 'bla', 'b' => 'omg');
if (array_search('bla', $something)) {
echo "|3| The 'bla' value found in the assoc array ||";
}
/**++++++++++++++++++++++++++++++++++++++++++++++
* 4. trying with isset (fastest ever)
*
* isset — Determine if a variable is set and
* is not NULL
*++++++++++++++++++++++++++++++++++++++++++++++
*/
$something = array('a' => 'bla', 'b' => 'omg');
if($something['a']=='bla'){
echo "|4| Yeah!! 'bla' found in array ||";
}
/**
* OUTPUT:
* |1| The 'omg' element value found in the assoc array ||
* |2| The 'omg' element value found in the index array ||
* |3| The 'bla' element value found in the assoc array ||
* |4| Yeah!! 'bla' found in array ||
*/
?>
Here is PHP DEMO
Using the instruction if
?
if(isset($something['say']) && $something['say'] === 'bla') {
// do something
}
By the way, you are assigning a value with the key say
twice, hence your array will result in an array with only one value.
You can use:
array_search()
in_array()
- a combination of
array_flip()
andarray_key_exists()