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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.