How to add elements in an array dynamically in php?

by jasen_gottlieb , in category: PHP General , 6 months ago

How to add elements in an array dynamically in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a month ago

@jasen_gottlieb 

You can add elements to an array dynamically in PHP using the array_push() function. Here's an example:

1
2
3
4
5
6
7
8
9
// Initialize an empty array
$myArray = [];

// Add elements to the array dynamically
array_push($myArray, "element1");
array_push($myArray, "element2");

// Print the array
print_r($myArray);


This code will add two elements "element1" and "element2" to the $myArray array using the array_push() function. You can continue to use array_push() to add more elements dynamically to the array as needed.