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 can I check if 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:

<?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!

Comments on this Question/Answer

How to search any value in an array. I want to search the value is parent in an array or not.
By: Sunil, 26 Jun 2009 21:40:34



Reply to comments / post your own comment >>>

ASK A QUESTION

More arrays PHP Questions

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

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

How can I reverse sort an array keeping the correlation between the index and value?

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?

How can I display a 2 dimensonal array?



Custom Search