phparraysforeachvariable-assignment

How to populate array using foreach loop in php?


Given an array. How to create a new array by iterating given array using foreach loop?

My attempt:

<?php /* version +7 */

$input = array("teamA", "teamB", "teamC");

foreach ($input as &$value) {
    $assign = "50"; /* The data just temp */
    $data = array($value => $assign);
}

echo $data["teamA"];

?>

Solution

  • I suppose you're looking for this:

    $input = array("teamA","teamB","teamC");
    $data = [];
    foreach($input as $value){
        $assign = "50"; /* The data just temp */
        $data[$value] = $assign;
    }
    
    echo $data["teamA"];
    

    If $assign is same for all keys:

    $data = array_fill_keys($input, 50);