Page 1 of 1
making variables from an associative array
Posted: Tue Apr 21, 2009 12:55 pm
by dkblb
I am sure this is something simple I am missing but I have been trying to find a way to access the current and next key/value of an associative array but can't make it work. If I want all key/value combinations this works:
foreach($matrix0 as $pair => $distance)
echo $pair." ".$distance."\n";
But I want to convert the key and value to variable and work with them one at a time. Thanks.
Re: making variables from an associative array
Posted: Tue Apr 21, 2009 1:04 pm
by requinix
dkblb wrote:But I want to convert the key and value to variable and work with them one at a time.
And what does that mean?
Fun stuff:
-
array_keys will give you an array of just the keys.
-
array_values is its counterpart.
-
list lets you extract stuff from an array into multiple variables.
- Instead of foreach there's also
each,
next,
current, and
key.
If none of those help you then it'd be great if you could explain what you're trying to do.
Re: making variables from an associative array
Posted: Tue Apr 21, 2009 1:33 pm
by dkblb
What I have been trying to do is use current, next and each and convert the present key and value to variables without success. I would be grateful for the correct syntax. Thanks.
Re: making variables from an associative array
Posted: Tue Apr 21, 2009 2:25 pm
by requinix
each/next and foreach do the same thing: you get to see each key/value pair one-at-a-time.
Again: what are you trying to do?
Re: making variables from an associative array
Posted: Tue Apr 21, 2009 2:56 pm
by dkblb
I have two similar associative arrays matrix and $matix0 having a identical structure; $pair as the key in $matrix with $distance the value. $matrix0 has $pair1 as key and $distance1 as value. I want to compare these values writing the lower $distance value to a mysql table. To do that I need to have both $pair and $distance as variables. One of the many approaches I have tried is
current($matrix as $pair => $distance);
current($matrix0 as $pair1 => $distance1);
Which I hoped would give me 4 variables; $pair, $pair1, $distance and $distance1. But it doesn't and I hope you can help. Thanks.