3v4l.org

run code in 300+ PHP versions simultaneously
<?php // arr1 $a = ['tip1', 'tip2', 'tip3', 'tip4', 'tip5']; $x = new stdClass(); $x->denumireTip = 'tip1'; $x->valoare = 8; $y = new stdClass(); $y->denumireTip = 'tip3'; $y->valoare = 14; $z = new stdClass(); $z->denumireTip = 'tip4'; $z->valoare = 2; // arr2 $b = [$x, $y, $z]; // arr2 cu cheile schimbate in denumireTip -> sa fie unice $c = []; foreach ($b as $value) { $c[$value->denumireTip] = $value; } // arr3 - rezultatul $d = []; foreach ($a as $value) { if (isset($c[$value])) { $d[] = $c[$value]; } else { $o = new stdClass(); $o->denumireTip = $value; $o->valoare = 0; $d[] = $o; unset($o); } } var_dump($d);
Output for 7.1.25 - 7.1.32, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.27, 8.0.0 - 8.0.15, 8.1.0 - 8.1.2
array(5) { [0]=> object(stdClass)#1 (2) { ["denumireTip"]=> string(4) "tip1" ["valoare"]=> int(8) } [1]=> object(stdClass)#4 (2) { ["denumireTip"]=> string(4) "tip2" ["valoare"]=> int(0) } [2]=> object(stdClass)#2 (2) { ["denumireTip"]=> string(4) "tip3" ["valoare"]=> int(14) } [3]=> object(stdClass)#3 (2) { ["denumireTip"]=> string(4) "tip4" ["valoare"]=> int(2) } [4]=> object(stdClass)#5 (2) { ["denumireTip"]=> string(4) "tip5" ["valoare"]=> int(0) } }

preferences:
47.08 ms | 462 KiB | 5 Q