PHP Questions Home
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

How do I find out if a value is already in an array?


If you don't have a particular requirement for this at the moment, then almost certainly at some time in your PHP programming career you will need to know whether an element is already in an array or not. If it is, you will usually want to take one course of action, and if it isn't, another.

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



ASK A QUESTION

More arrays PHP Questions

I am not interested in the values in the arrays, how can I discard them?

OK I've been trying to echo out the arrays "$people and $other people" using the for-each method in alphabetical order. but when i see what this displays it does it in some other order. THIS IS THE CODE PHP Ch8 Lab

How do I generate an associative array like Jan => 10, Feb =>20 etc from a mysql table of 2 columns, month and val ?

How do I remove and view the last element of an array?

How do I add to the beginning of an array and find the number of elements in it?



Custom Search