Reputation: 9123
I am trying to use variable variables. By using $type
in a foreach loop, I would like to get the value of $week['one']
and $month['one']
.
$types = array(
'week',
'month'
);
$week = array(
'one' => 1.2,
'two' => 0.13,
);
$month = array(
'one' => 1.2,
'two' => 0.13,
);
Methods I've tried without success:
<?php foreach ($types as $type): ?>
<?= $$type['one']; ?><br />
<?= $$type['two']; ?><br />
<?php endforeach; ?>
<?php foreach ($types as $type): ?>
<?= ${$type}['one']; ?><br />
<?= ${$type}['two']; ?><br />
<?php endforeach; ?>
<?php foreach ($types as $type): ?>
<?= $($type)['one']; ?><br />
<?= $($type)['two']; ?><br />
<?php endforeach; ?>
Everything seems to resul in syntax errors. Am I using the wrong syntax?
Upvotes: 1
Views: 45
Reputation: 5011
Use this variant:
<?php foreach ($types as $type): ?>
<?= ${$type}['one']; ?><br />
<?= ${$type}['two']; ?><br />
<?php endforeach; ?>
Check it here: https://3v4l.org/H7Pn7.
Upvotes: 1