0

I have this script that gets weather data from a API. But I need to have the temperatures of every day in seperate strings. $day1Max, $day1Min, $day2Max, $day2Min, etc...

Is it possible to get these variables from a foreach loop?

<?php

$conditions_week = $forecast->getForecastWeek($latitude, $longitude);

echo "Forecast this week:\n";

foreach($conditions_week as $conditions) {
?>  
    
<tr>
<th><?php     echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMaxTemperature() . "\n"; ?></th>
<th><?php     echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMinTemperature() . "\n"; ?></th>
</tr>
<?php
}
?>

This is the output:

enter image description here

1 Answer 1

1

Here is your solution :

<?php

class Conditions{
    function __construct($min,$max){
         $this->max = $max;
         $this->min = $min;
    }

    function getMaxTemperature(){
        return $this->max;
    }
    function getMinTemperature(){
        return $this->min;
    }
}

$conditions_week = array(new Conditions(5,10),new Conditions(-5,3));

echo "Forecast this week:\n";

foreach($conditions_week as $k=>$conditions) {
$varMin = "day".($k+1)."min";
$varMax = "day".($k+1)."max";
$$varMin = $conditions->getMinTemperature();
$$varMax = $conditions->getMaxTemperature();
?>  

<tr>
<th><?php     echo "Max : ". $conditions->getMaxTemperature() . "\n"; ?></th>
<th><?php     echo "Min : ". $conditions->getMinTemperature() . "\n"; ?></th>
</tr>
<?php

}


echo "day1min : " . $day1min;
echo '<br>';
echo "day1max : " . $day1max;
echo "<hr>";
echo "day2min : " . $day2min;
echo '<br>';
echo "day2max : " . $day2max;

You to generate your php variables $day1min, $day1max... inside the foreach and then you can use it outside the loop.

Here's the full example : https://3v4l.org/vX5bW

Sign up to request clarification or add additional context in comments.

1 Comment

You're the proof that not all heroes wear capes! Thank you sir, this works perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.