Search code examples
phparraysstringcellarray-push

array_push into a multidimensional array (append a value to cell)


This is my code :

$cars = array(
    array("Volvo" , '22,18,'),
    array("BMW" , '15,13'),
    array("Saab", '5,2' ),
    array("Land Rover", '17,15' )
);

print_r($cars);

this is the output :

Array ( [0] => Array ( [0] => Volvo [1] => 22,18, ) [1] => Array ( [0] => BMW [1] => 15,13 ) [2] => Array ( [0] => Saab [1] => 5,2 ) [3] => Array ( [0] => Land Rover [1] => 17,15 ) ) 

I want to dynamically push values into (for example) the string numeric values inside that multidimensional array but not overwrite the existed cell (as the same as you append to string $string .= $string.' + Extra Content';)

for example this is the original :

array("Volvo" , '22,18,'),

lets add '21,' and later lets add '27,' and later lets add '14,'

DYNAMICALLY under that specific cell.

so by the end of the day it would be :

array("Volvo" , '22,18,21,27,14,')

Is that possible ?


Solution

  • Sample solution with comments explaining it step by step (for PHP >= 5.5) For PHP < 5.5 you can use array_walk combination

    <?php
    
    $cars = array(
        array("Volvo" , '22,18,'),
        array("BMW" , '15,13'),
        array("Saab", '5,2' ),
        array("Land Rover", '17,15' )
    );
    
    print_r($cars);
    
    $labels = array_column($cars, 0); // Get list of car manufacturers PHP>=5.5
    $labels = array_map(function($element){return $element[0];}, $cars); // Get list of car manufacturers PHP 4+
    $id = array_search('Volvo', $labels); // Find id of 'Volvo'
    $cars[$id][1].='21,'; //append value
    $cars[$id][1].='27,'; //append value
    
    print_r($cars);
    

    Which u can test on ideone