Besnik Cani Besnik Cani - 1 year ago 65
PHP Question

How do I get to show the name of the array inside another array

So I had a question in an interview and it says something like this: Find the tire with the best average score in all conditions and if a tire has scored less than 5 in any condition it is disqualified.

$tires=[
'Desert'=>array('dry'=>10, 'wet'=>4, 'snow'=>1),
'Ocean'=>array('dry'=>6, 'wet'=>8, 'snow'=>6),
'RainForest'=>array('dry'=>6, 'wet'=>10, 'snow'=>6),
'Glacier'=>array('dry'=>4, 'wet'=>9, 'snow'=>10),
'Prairie'=>array('dry'=>7, 'wet'=>7, 'snow'=>7),
];
$max=0;
foreach($tires as $key){
$total=0;
foreach($key as $condition=>$score){
if($score>5){
$total=$total+$score;
}else{
$total=-150000;
}
}
$total=$total/3;
if($total>$max){
$max=$total;
$bestTire=$key;
}
}
echo $bestTire." is the best tire with the score: ".$max;


The output says:Notice: Array to string conversion in C:\xampp...
Array is the best tire with the score: 7.3333333333333

The question is how do I get to show the name 'RainForest' instead of 'Array'

Thank you

Answer Source

you have confusing names, fix them:

$tires=[
  'Desert'=>array('dry'=>10, 'wet'=>4, 'snow'=>1),  
  'Ocean'=>array('dry'=>6, 'wet'=>8, 'snow'=>6),  
  'RainForest'=>array('dry'=>6, 'wet'=>10, 'snow'=>6),  
  'Glacier'=>array('dry'=>4, 'wet'=>9, 'snow'=>10),  
  'Prairie'=>array('dry'=>7, 'wet'=>7, 'snow'=>7),  
];
$max=0;
foreach($tires as $tier => $conditions){ // note key and value
    $total=0;
    foreach($conditions as $condition => $score){ // note array name
        if($score>5){
            $total=$total+$score;
        }else{
            $total=-150000;
        }
    }
    $total=$total/3;
    if($total>$max){
        $max=$total;
        $bestTire = $tier; // note key name
    }
}
echo $bestTire." is the best tire with the score: ".$max;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download