making variables from an associative array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dkblb
Forum Newbie
Posts: 8
Joined: Wed Apr 15, 2009 3:30 pm

making variables from an associative array

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: making variables from an associative array

Post 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.
dkblb
Forum Newbie
Posts: 8
Joined: Wed Apr 15, 2009 3:30 pm

Re: making variables from an associative array

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: making variables from an associative array

Post 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?
dkblb
Forum Newbie
Posts: 8
Joined: Wed Apr 15, 2009 3:30 pm

Re: making variables from an associative array

Post 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.
Post Reply