Reputation: 17
I am trying to get the values between min and max in a PHP object.
This is the output of the PHP object:
var_dump($suggestions->productionYear);
Outputs:
object(stdClass)#6567 (2) { ["min"]=> int(2016) ["max"]=> int(2019) }
But I want to output all the values between the min
and max
like this: 2016
, 2017
, 2018
and 2019
Does someone know how I get the output like above? I know I have to use a foreach loop but everytime I get output NULL
<?php foreach ($suggestions->productionYear as $productionYear) { ?>
<option value="<?php echo $productionYear; ?>"
><?php echo $productionYear; ?></option>
<?php } ?>
Thanks for your time!
Upvotes: 0
Views: 611
Reputation: 146588
Neither min
nor max
have any special meaning in PHP objects as you seem to assume. If you want your object to be iterable with foreach
you need to make it implement the Iterator
interface. You can find a full implementation at Example #1 Basic usage.
Otherwise, just build your own loop or generate a range:
$suggestions = (object)null;
$suggestions->productionYear = (object)['min' => 2016, 'max' => 2019];
for ($productionYear = $suggestions->productionYear->min; $productionYear <= $suggestions->productionYear->max; $productionYear++) { ?>
<option value="<?php echo $productionYear; ?>"><?php echo $productionYear; ?></option>
<?php }
foreach (range($suggestions->productionYear->min, $suggestions->productionYear->max) as $productionYear) { ?>
<option value="<?php echo $productionYear; ?>"><?php echo $productionYear; ?></option>
<?php }
Upvotes: 1
Reputation: 38542
You can use range()
with foreach()
, See: https://www.php.net/manual/en/function.range.php
foreach (range($min, $max) as $year) {
// other code goes here
}
For your case something like,
$min = $suggestions->productionYear->min;
$max = $suggestions->productionYear->max;
<?php foreach (range($min,$max) as $year) { ?>
<option value="<?php echo $year; ?>"
><?php echo $year; ?></option>
<?php } ?>
Upvotes: 2
Reputation: 675
As you can see on var_dump, it outputs an object. So you first need to convert that into an array and then loop over it.
(array) $suggestions->productionYear;
Upvotes: 0