Tuesday, July 14, 2009

How can you check that a value is already in an array?

If you wish to check whether a value is already stored in an array or not, then use the in_array function.

This is useful when you don't want any duplicates in the array and therefore only want to add a value if it's not already there. The first argument is the string you are testing for and the second is the array you are checking against.

Here is an example of in_array in action:

$values = array("banana","apple","pear","banana");
$newvalue = "pear";
if (
in_array($newvalue,$values)) { echo "$newvalue is already in the array!"; }
?>

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home