1

I'm trying to add element in an array dynamically.

Here's my code:

$tasks = [];

$task = [
'title' => 'task title',
'description' => 'task description'
];

array_push($tasks, $task);

When I'm doing that task is added in an array, but when I copy task variable and change its content I expect to update an array, instead previously added task is replaced.

2 Answers 2

1

Arrays aren't passed by reference in PHP, only objects are.

You may want to use a reference:

$tasks = [];
$task = [
    'title' => 'task title',
    'description' => 'task description'
];
$tasks[] = &$task;
$task['title'] = 'Modified';
var_dump($tasks);
array(1) {
  [0] =>
  array(2) {
    'title' =>
    string(8) "Modified"
    'description' =>
    string(16) "task description"
  }
}

Beware though that references are a feature of their own and don't behave exactly as object-passing does. If you need this behaviour, I strongly recommend you to switch to objects.

$tasks = [];

class Task
{
    public function __construct(
        public string $title,
        public string $description
    ) {
    }
}

$task = new Task('task title','task description');
$tasks[] = $task;
$task->title = 'Modified';
var_dump($tasks);
array(1) {
  [0] =>
  class Task#1 (2) {
    public string $title =>
    string(8) "Modified"
    public string $description =>
    string(16) "task description"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

just use the built in push using []

$tasks = [];

$tasks[] = [
'title' => 'task title',
'description' => 'task description'
];

Comments

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.