Wednesday, August 22, 2018

PHP Foreach Key by Pointer


Here is a way to add new elements to new array in PHP foreach, by reference on 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);

No comments:

Post a Comment