Tuesday 6 April 2021

Php: in_array: Check for existence of an element

Signature

in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool

 

Description

Checks if a value exists in an array. Returns true if needle is found in the array, false otherwise.

 

Parameters

needle: Value to be searched.

 

haystack: 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 array.

 

Example

$is_9_exist = in_array(9, $arr1);

$is_char_9_exist = in_array('9', $arr1);

$is_char_9_exist_strict_comp = in_array('9', $arr1, true);

 

in_array_demo.php

#!/usr/bin/php

<?php

    $arr1 = array(22, 31, -5, 9, 77, -98, 18);
    
    $is_9_exist = in_array(9, $arr1);
    $is_char_9_exist = in_array('9', $arr1);
    $is_char_9_exist_strict_comp = in_array('9', $arr1, true);

    echo "Is 9 exist in the array : ";
    var_dump($is_9_exist);

    echo "\nIs '9' exist in the array : ";
    var_dump($is_char_9_exist);

    echo "\nIs '9' exist in the array (stricct comparison) : ";
    var_dump($is_char_9_exist_strict_comp);
?>

 

Output

$./in_array_demo.php 

Is 9 exist in the array : bool(true)

Is '9' exist in the array : bool(true)

Is '9' exist in the array (stricct comparison) : bool(false)

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment