How can I check if a value is already in an array?
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:
<?php
$values = array("banana","apple","pear","banana");
$newvalue = "pear";
if (in_array($newvalue,$values)) { echo "$newvalue is already in the array!"; }
?>
The most common mistake made with in_array is to pass the arguments in the wrong order to the function, so take care!
More arrays PHP Questions
How do I find the size of an array?How do I turn an array into a string?
How do I sort an array by key?
How do I remove the first element from an array?
How do I check if a variable is of array type?