Showing posts with label element. Show all posts
Showing posts with label element. Show all posts

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

Thursday, 1 April 2021

Php: Add an element to the array

Syntax

$array_name[] = new_value;

 

Example

$arr1[] = 11;

 

Above statement add the number 11 to the end of the array. Find the below working application.

 

array_add_element.php

#!/usr/bin/php

<?php
$arr1 = array(
    2,
    3,
    5,
    7
);

print_r($arr1);

echo "\nAdding another element 11 to arr1\n";

$arr1[] = 11;
print_r($arr1);

echo "\nAdding another element 13 to arr1\n";

$arr1[] = 13;
print_r($arr1);
?>

 

Output

$./array_add_element.php 

Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 7
)

Adding another element 11 to arr1
Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 11
)

Adding another element 13 to arr1
Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 11
    [5] => 13
)

 

 

 

  

Previous                                                    Next                                                    Home