How can I check if a value is already in an array?

Answers were Sorted based on User's Feedback



How can I check if a value is already in an array? ..

Answer / mohammed khalid khan

The first answer is not complete.
&
The second answer is correct.


<?php
$values = array("banana","apple","pear","banana");
if (in_array("pear",$values))
{
echo "Got pear";
}
?>

Is This Answer Correct ?    6 Yes 0 No

How can I check if a value is already in an array? ..

Answer / jude jeevanraj.p

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

Is This Answer Correct ?    7 Yes 2 No

How can I check if a value is already in an array? ..

Answer / deep

The above answer is correct. I will just add a complete
example.

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os))
{
echo "Got Irix";
}
if (in_array("mac", $os))
{
echo "Got mac";
}
?>

Is This Answer Correct ?    7 Yes 2 No

Post New Answer

More PHP Interview Questions

Tips to optimize the php script..... Suggestion for exception handling in php...

1 Answers  


How to find out, how a user visited a particular page?

4 Answers   Yahoo,


what is the difference between GET,POST and REQUEST in php

1 Answers  


What is the php function that removes the last element of the array and returns it?

0 Answers  


Who is the father of php?

0 Answers  


How to remove the new line character from the end of a text line in php?

0 Answers  


How to run the interactive php shell from the command line interface?

0 Answers  


How can we access the data sent through the url with the post method?

0 Answers  


Tell me how is it possible to propagate a session id?

0 Answers  


How to set a page as a home page in a php based site?

0 Answers  


How big is varchar max?

0 Answers  


How can we set and destroy the cookie in php?

0 Answers  


Categories