I have the following array content:
Array ( [achternaam] => Jansen [roepnaam] => Theo )
Now i want to use this code
foreach ($values as $r) {
$achternaam = $r['achternaam'];
$roepnaam = $r['roepnaam'];
}
开发者_如何学JAVA
When want to echo the $achternaam and $voornaam the values are empty. Does anyone know how to bind this variables to eachother.
The result should be $achternaam = Jansen and $roepnaam = Theo.
Tnx for helping!
$values = array(
'achternaam' => 'Jansen',
'roepnaam' => 'Theo'
);
The elements of $values
are strings, not arrays. To access the achternaam
and roepnaam
values, you need to remove the foreach:
$achternaam = $values['achternaam'];
$roepnaam = $values['roepnaam'];
If the positions of the achternaam
and roepnaam
keys do not change, you may use list
as well:
list($achternaam, $roepnaam) = $values;
This is only possible if the keys are in the order achternaam
, roepnaam
. I.e. $values['achternaam']
needs to assigned before $values['roepnaam']
.
this should work:
$values = array('achternaam' => 'Jansen', 'roepnaam' => 'Theo');
list($achternaam, $roepnaam) = $values;
try it though...
Use a nested array if you want to have more than one person:
<?php
$values = array(
array(
'achternaam' => 'Jansen',
'voornaam' => 'Theo',
'club' => 'Ajax'
)
);
foreach ($values as $r) {
$achternaam = $r['achternaam'];
$roepnaam = $r['roepnaam'];
echo $roepnaam . ' ' . $achternaam;
}
If you want to keep using that array though, you can do it without foreach:
<?php
$values = array(
'achternaam' => 'Jansen',
'voornaam' => 'Theo',
'club' => 'Ajax'
);
$achternaam = $values['achternaam'];
$roepnaam = $values['roepnaam'];
echo $roepnaam . ' ' . $achternaam;
It looks like you're misunderstanding how foreach
works. For each iteration of the loop, your variable $r
has a string value - "Jansen" the first time and "Theo" the second.
The result you're trying to achieve can be done like this:
foreach($values as $k => $r) {
$$k = $r;
}
Be careful where your array keys are coming from though - as this code could overwrite other sensitive variables in your script.
How about one simple line of code:
extract($values)
http://php.net/manual/en/function.extract.php
精彩评论