Skip to content
PHP Logo

How can you fill an array with dynamic data in PHP?

To fill an array with dynamic data in PHP, you can use a loop to iterate over the data source (such as a database query result or an API response) and add each item to the array. This allows you to dynamically populate the array with the data you need.

php
// Example code to fill an array with dynamic data
$dynamicData = []; // Initialize an empty array

// Simulated dynamic data source
$dataSource = ['item1', 'item2', 'item3'];

foreach ($dataSource as $item) {
    $dynamicData[] = $item; // Add each item to the array
}

// Now $dynamicData array contains ['item1', 'item2', 'item3']