0

In my class, I have a public variable:

public $full_rows = array("text");

I want to be able to add to that array, like so:

$form->addarray("full_rows", array("url","name"));

So I have this function:

public function addarray($arrayname, $array = array()) {
    array_merge($this->$arrayname, $array);     
}

Except it's not affecting the array full_rows at all. Why not?

Edit Thanks to roullie for the correct answer. Turns out I'd forgotten that array_merge returns the merged array rather than just doing it. I thought it was a problem with variable variables (as I'd never used them before).

Here is my final function:

public function addarray($arrayname, $array = array()) {
    if((isset($this->$arrayname)) && (is_array($array))) {
        $this->{$arrayname} = array_merge($this->{$arrayname}, $array);
    } else {
        return false;   
    }
}
1
  • $form->addarray($form->full_rows, array("url","name")); ? Commented Dec 11, 2015 at 8:18

1 Answer 1

1

set the value of the merged array to your $full_rows

public function addarray($arrayname, $array = array()) {
    $this->$arrayname = array_merge($this->$arrayname, $array);     
}
Sign up to request clarification or add additional context in comments.

2 Comments

Aah, I screwed up on array_merge. Thank you! But can you tell me why I couldnt write this: $this->$arrayname[] = "foo"; ?
Aah I figured it out. It needs to be: $this->{$arrayname}[] = "foo";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.