Wednesday, August 22, 2018

PHP Foreach Key by Pointer


Here is a way to add a new elements to a new array in PHP foreach function, by reference on a new element.


$items = Item::get();
$formattedItems = [];

foreach ($items as $item) {
    $fm = &$formattedItems[];
    $fm['id'] = $item->id;
    $fm['label'] = $item->label;
    $fm['icon'] = $item->icon;
}


var_dump($formattedItems);


Simple and clean.

No comments:

Post a Comment