Home > Software design >  how to add elements in an array dynamically in PHP
how to add elements in an array dynamically in PHP

Time:05-06

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.

CodePudding user response:

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"
  }
}

CodePudding user response:

just use the built in push using []

$tasks = [];

$tasks[] = [
'title' => 'task title',
'description' => 'task description'
];
  •  Tags:  
  • php
  • Related