D
dman_2007
Guest
If want to search an array to see if it currently holds a particular value or not, then you have a couple options which you can use :
1) in_array function
in_array function takes two required arguments, first is the value which is being searched and second is the array which is to be searched for the presence of that particular value. in_array function will return true if it finds the value in the array otherwise it returns false. If the value being searched is a string then comparison will be case-sensitive. Also, note that in_array uses == by default for comparison, so it will match 0 to "invalidnumberstring" for example. If you want in_array to use === for comparison, you can indicate this to in_array by passing a boolean value true as third argument. Here's an example :
the above code produces following output :
in my next post i will discuss the second method.
1) in_array function
in_array function takes two required arguments, first is the value which is being searched and second is the array which is to be searched for the presence of that particular value. in_array function will return true if it finds the value in the array otherwise it returns false. If the value being searched is a string then comparison will be case-sensitive. Also, note that in_array uses == by default for comparison, so it will match 0 to "invalidnumberstring" for example. If you want in_array to use === for comparison, you can indicate this to in_array by passing a boolean value true as third argument. Here's an example :
Code:
<?php
$array1 = array(1, 2, 3, 4, 5, 6, 'joe');
if(in_array(1, $array1))
{
echo '1 is present in the array<br />';
}
if(in_array(0, $array1))
{
echo '0 is present in the array (when not passing third argument)<br />';
}
if(in_array(0, $array1, true))
{
echo '0 is present in the array (when passing third argument)<br />';
}
else
{
echo '0 is not present in the array (when passing third argument)<br />';
}
if(in_array('JOE', $array1))
{
echo 'JOE is present in the array<br />';
}
else
{
echo 'JOE is not present in the array<br />';
}
?>
the above code produces following output :
1 is present in the array
0 is present in the array (when not passing third argument)
0 is not present in the array (when passing third argument)
JOE is not present in the array
in my next post i will discuss the second method.