Skip to content
PHP Logo

What are the best practices for filling an array in PHP within a loop?

When filling an array in PHP within a loop, it is important to initialize the array outside the loop and then add elements to it within the loop. This ensures that the array is not re-initialized in each iteration of the loop, which can lead to data loss. Additionally, using array_push() or the [] syntax to add elements to the array is more efficient than manually assigning values to specific array keys.

php
// Initialize an empty array
$array = [];

// Loop to fill the array with values
for ($i = 0; $i < 10; $i++) {
    $array[] = $i; // Add elements to the array using the [] syntax
}

// Print the array
print_r($array);