Thursday, December 5, 2013

How to use in_array() function in PHP

To check a variable exists in array you can use in_array() function:
Syntax: bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Parameters

needle
The searched value.
Note:
If needle is a string, the comparison is done in a case-sensitive manner.
haystack
The array.
strict
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return Values

Returns TRUE if needle is found in the array, FALSE otherwise.   
Example #1:
<?php
$fruit 
= array("apple""banana""orange");
if (
in_array("apple"$fruit)) {
    echo 
"apple exist in $fruit array";
}
if (!
in_array("iphone"$fruit)) {
    echo 
"iphone not exist in $fruit array";
}
?>
Example #2:
<?php
$fruit 
= array("1""2""4","7");
if (
in_array("1"$fruit)) {
    echo 
"Yes";
}
else
{
    echo "No";
}
?>
Example check array in array:
<?php
$a 
= array(array('a''e'), array('c''b'), 'd');

if (
in_array(array('a''e'), $a)) {
    echo 
"Found";
}
else
{
    echo "Not found";
}
if (
in_array(array('f''i'), $a)) {
    echo 
"Yes";
}

else
{
    echo "No";
}
if (in_array('d'$a)) {
    echo 
"'d' was found";
}
?>

1 comment: