Search code examples
phparrayspropertiesarray-merge

How to add items to class property array in php?


I have a class property which is an array. I have some $data array which I would like to add to that array without using a foreach loop.

Check out this sample code:

<?php
    class A {
    public $y = array();
    public function foo() {
        $data = array('apples', 'pears', 'oranges');
        array_merge($this->y, $data);
    }
}

$a = new A();
$a->foo();
print_r($a->y);
assert(sizeof($a->y)==3);

Expected result:

Array (
    [0] => apples
    [1] => pears
    [2] => oranges
)

Actual result:

Array ( )
PHP Warning:  assert(): Assertion failed on line 16

Solution

  • Change the function definition as follows:

    public function foo() {
            $data = array('apples', 'pears', 'oranges');
            $this->y = array_merge($this->y, $data);
    }
    

    The documentation clearly states that the merged array is returned back. So, the original array passed in the parameter remains untouched.