Search code examples
phpfunctionmultidimensional-arrayassociative-arrayarray-push

PHP problem with array_push(mainArr, subAssociativeArr) inside a function


the array_push(mainArr, subAssociativeArr) does not work when it is inside a function. I need some help with this code:

$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');

function addOne($store, $element){
    array_push($store, $element);
}
addOne($store, $samsung);

var_dump($store); //output: empty array 

however it works fine if without function; like the following:

$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');
array_push($store, $samsung);
var_dump($store); //output: array is added 

so, what is the problem???


Solution

  • You forgot to return

    function addOne($store, $element){
        $store[]=$element;
        return $store;
    }
    $store = addOne($store, $samsung);
    

    You could also pass by reference if you want to (which is more in line with the code you have):

    function addOne(&$store, $element){
        $store[]=$element;
    }
    addOne($store, $samsung);
    

    Note the &. Instead of copying the inputs, this is more like a pointer to the original variable, so you can update it directly. Ether way is fine here, it's a matter of developers choice really. For example it can be very easy to mix the two:

    //Don't do this
    function addOne(&$store, $element){ //returns null
        $store[]=$element;
    }
    $store = addOne($store, $samsung); //sets $store to null
    

    Which you probably don't want to do, so I can see an argument for both ways. Unless you have super big array, it probably doesn't matter much. It's very easy to forget that a random function is pass by reference.

    So use whatever method makes more sense to you.

    P.S. - I refuse to use array_push, it's ugly and I don't like it :). Doing $store[]=$element; is the same as array_push($store,$element), except it avoids an unnecessary function call.

    Cheers.