How to push data into array in php?

by herminia_bruen , in category: PHP General , 8 months ago

How to push data into array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 8 months ago

@herminia_bruen 

To push data into an array in PHP, you can use the array_push() function or directly assign values to the array.


Here are two ways to push data into an array:

  1. Using array_push(): $myArray = []; // Declaring an empty array array_push($myArray, "data1"); // Pushing "data1" into $myArray array_push($myArray, "data2"); // Pushing "data2" into $myArray
  2. Directly assigning values: $myArray = []; // Declaring an empty array $myArray[] = "data1"; // Pushing "data1" into $myArray $myArray[] = "data2"; // Pushing "data2" into $myArray


In both cases, the resulting array would be: ["data1", "data2"]