How do I find out if a value is already in an array?
PHP provides a very useful function called in_array that lets you check whether a value is already in the array or not. Here is an example of it in use when we want to check if certain numbers are present in an array or not:
<?php
$numbers = range(1,10);
$checknumbers = array(1,20,10);
foreach($checknumbers as $isitthere) {
if(in_array($isitthere,$numbers)) { echo "The number $isitthere is in the numbers array\n\n"; }
else { echo "The number $isitthere is NOT in the numbers array\n\n"; }
}
?>
This prints:
The number 1 is in the numbers array
The number 20 is NOT in the numbers array
The number 10 is in the numbers array
Comment on this Question and Answer >>>
ASK A QUESTION
More arrays PHP Questions
How do I remove an element from an array without changing the index values for the rest of the array?How can I display a 2 dimensonal array?
How do I remove the first element from an array?
How can I reset an array in PHP?
I'm shuffeling through numbers range(1, 10). Can I eval resulting random numbers and convert to appropriate text? 1 = username1, 2 = username2...etc?
