For some reason I keep getting this notice when I try to loop through an array and change it's values.
For some reason, the array is passing 2 values, the one before and the one after when running the same function that changes the values.
class UnitConverter {
public $vulgar_to_float = array('½' => '1/2');
public function replaceUnicode($amount){
foreach($this->vulgar_to_float as $key => $float){
if(is_numeric($amount)){
return $amount;
} else if($key === $amount){
return $float;
}
}
}
public function convertAmount($amount, $from, $to){
if($from === 'pound' && $to === 'ounce'){
return $amount * 16;
} else if($from === 'cup' && $to === 'tablespoon'){
print_r($amount); // here it's echoing 2 values when it should be 1
return $this->replaceUnicode($amount) * 16;
} else {
throw new \Exception('Unable to convert ' . $from . ' to ' . $to);
}
}
}
function convertIngredients($arr){
foreach($arr as $key => $value){
if($arr[$key]['unit_name'] === 'pound'){
$arr[$key]['amount'] = (new UnitConverter())->convertAmount($arr[$key]['amount'], 'pound', 'ounce');
$arr[$key]['unit_name'] = 'ounce';
} else if($arr[$key]['unit_name'] === 'cup'){
$arr[$key]['amount'] = (new UnitConverter())->convertAmount($arr[$key]['amount'], 'cup', 'tablespoon');
$arr[$key]['unit_name'] = 'tablespoon';
}
}
return $arr;
}
function generateBreakfast(){
$array = $var = array(
0 => array( 'amount' => 1, 'ingredient_name' => 'almond flour', 'unit_name' => 'cup' ),
1 => array( 'amount' => ½, 'ingredient_name' => 'erythritol', 'unit_name' => 'cup' ),
2 => array( 'amount' => 1, 'ingredient_name' => 'egg', 'unit_name' => 'large' )
);
$converted_ingredients = convertIngredients($array);
return $converted_ingredients;
}
echo '<pre>';
print_r(generateBreakfast());
echo '</pre>';
So in the convertIngredients, we're calling the convertAmount method, but for some reason there.. it's passing this '1½' instead of just calling the method individually with each iteration.
If you take a look here: https://eval.in/944452 , the amount in erythritol is showing 16, but it should be 8 because 1/2 of 16 = 8.