3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Example { public $length, $height, $width, $weight; public function __construct($length, $height, $width, $weight) { $this->length = $length; $this->height = $height; $this->width = $width; $this->weight = $weight; } public function get_price() { return 1.23; } } $sample_data = [ 42 => ['quantity' => 2, 'data' => new Example(42, 42, 42, 42)], 69 => ['quantity' => 1, 'data' => new Example(69, 69, 69, 69)], ]; $i = 0; $totalweight = 0; $totalprice = 0; foreach ( $sample_data as $item_id => $values ) { $_product = $values['data']; $q = 1; while ( $values['quantity'] >= $q ) { $products[ $i ]->length = $_product->length; $products[ $i ]->height = $_product->height; $products[ $i ]->width = $_product->width; $products[ $i ]->weight = $_product->weight; $totalweight += $_product->weight; $totalprice += $_product->get_price(); $q++; $i++; } } var_dump($products);

preferences:
26.51 ms | 404 KiB | 5 Q