Create Array from Foreach
To create an array from a foreach loop in PHP, you can use the array push function array_push()
inside the loop. Here's an example:
<?php
$original_array = [1, 2, 3, 4, 5];
$new_array = [];
foreach ($original_array as $value) {
array_push($new_array, $value);
}
print_r($new_array);
?>
In this example, $original_array
is an array of integers, and $new_array
is an empty array. The foreach loop iterates through each value in $original_array
, and pushes that value onto the end of $new_array
using array_push()
. After the loop is finished, $new_array
will contain the same values as $original_array
.
Additionally, it is also possible to use the short array syntax from PHP 5.4 and above
<?php
$original_array = [1, 2, 3, 4, 5];
$new_array = [];
foreach ($original_array as $value) {
$new_array[] = $value;
}
print_r($new_array);
?>
Both examples will produce the same result.