Thursday, 1 April 2021

Php: Update values of array using reference

Using variable reference, you can update the values of array while iterating.

 

Example: Double each element in the array.

foreach($arr1 as &$ele){

    $ele = $ele * 2;

}

 

As you see the above snippet, I am using & to access the reference of each array value.

array_reference_values_update.php

#!/usr/bin/php

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

    echo 'Contents of array arr1 :';
    print_r($arr1);

    echo "\nDoubling the contents of array\n\n";
    foreach($arr1 as &$ele){
        $ele = $ele * 2;
    }

    echo 'Contents of array arr1 :';
    print_r($arr1);
?>

Output

$./array_reference_values_update.php 

Contents of array arr1 :Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 6
)

Doubling the contents of array

Contents of array arr1 :Array
(
    [0] => 4
    [1] => 6
    [2] => 10
    [3] => 12
)




 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment