Thursday 1 April 2021

Php: Add an element to associate array

Syntax

$array_name[key_name] = value;

 

Example

$arr1['country'] = 'India';

 

Find the below working application.

 

array_associative_add_element.php

#!/usr/bin/php

<?php
$arr1 = [
    'id' => 1,
    'age' => 32,
    'name' => 'Sailu',
    'male' => false
];

echo "Contents of arr1 are : \n";
print_r($arr1);

echo "\nAdding country key to the array\n";
$arr1['country'] = 'India';

print_r($arr1);

?>

 

Output

$./array_associative_add_element.php 

Contents of arr1 are : 
Array
(
    [id] => 1
    [age] => 32
    [name] => Sailu
    [male] => 
)

Adding country key to the array
Array
(
    [id] => 1
    [age] => 32
    [name] => Sailu
    [male] => 
    [country] => India
)

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment