Skip to content
PHP Logo

Is it possible to create an associative array in PHP within a foreach loop?

Yes, it is possible to create an associative array in PHP within a foreach loop. You can iterate over a set of data using a foreach loop and dynamically build an associative array by assigning key-value pairs within the loop. This allows you to easily create an associative array based on the data you are iterating over.

php
$data = [1, 2, 3, 4, 5];
$associativeArray = [];

foreach ($data as $value) {
    $associativeArray[$value] = $value * 2;
}

print_r($associativeArray);