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

No comments:

Post a Comment