Zaki Sulistya February 2016

Failed Using array_merge inside of PHP class

class Test
{
  public $data = array();

  public function addData($data = array())
  {
    array_merge($data, $this->data);
    return $this;
  }

  public function showData()
  {
    print_r($this->data);
  }
}
$test = new Test;
$test->addData(array("halo", "zaki"))->showData();

i tried to merging 2 array, but it doesn't work, maybe someone can explain to me?

Answers


Rajdeep Paul February 2016

You forgot to assign the resulting array to member variable $data. It should be,

$this->data = array_merge($data, $this->data);


Tom Wright February 2016

array_merge does not modify the arrays passed to it, but rather returns the result.

Try this:

public function addData($data = array())
{
    $this->data = array_merge($data, $this->data);
    return $this;
}

Post Status

Asked in February 2016
Viewed 1,728 times
Voted 11
Answered 2 times

Search




Leave an answer