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

What is the content of /etc directory?

0 Answers  


What are the advantages of indexes?

0 Answers  


Which is useful for method overloading?

0 Answers  


How to create connection in php?

0 Answers  


Is facebook still written in php?

0 Answers  


Why does sql injection happen?

0 Answers  


List few sensible functions in PHP?

0 Answers  


What happens when submit button is clicked?

0 Answers  


Define urlencode() and urldecode() used in php?

0 Answers  


Why delimiter is used in mysql?

0 Answers  


What's the difference between using mysql_ functions and pdo?

0 Answers  


Is php faster than python?

0 Answers  


Categories