How to add an item to array in laravel?

Member

by addison , in category: PHP Frameworks , 6 months ago

How to add an item to array in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 6 months ago

@addison 

To add an item to an array in Laravel, you can use the array_push() function. Here's an example:

1
2
3
4
5
$array = ['item1', 'item2', 'item3'];

array_push($array, 'newItem');

// The $array now contains ['item1', 'item2', 'item3', 'newItem']


Alternatively, you can also use the [] syntax to add an item to an array:

1
2
3
4
5
$array = ['item1', 'item2', 'item3'];

$array[] = 'newItem';

// The $array now contains ['item1', 'item2', 'item3', 'newItem']


These methods work for both indexed and associative arrays in Laravel.