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 send the information from one page to another page using post method.How can I display values in a two dimensional array?
How do I find if a value is already in an array or not?
How do I write my own sort function?
I have an array of a hundred or so lines, each line has data with "|" separated values. I need to scan through this array, and select the line whose first 5 characters matches a text string. Any ideas or questions?
