cdc

I don't use associative arrays as much as I should, but I'm starting to use them more often now.

Let's say I have an array that looks like this:

$myarray = array("key1"=>"val1", "key2"=>"val2");

What's the best way to iterate through this list? For regular arrays I would just do a foreach, but I'm guessing that will just give me the vals in the above example. Then I'd have to go back and look up the key for that val, which seems messy.

Any better way?

m0nkeymafia

I did this today Applause


foreach($kwCloud as $key => $value)
{
$key . ': '. $value;
}


$key refers to the name of the key
$value is its value.

If you wish to sort the array and keep the original keys use asort and arsort
Job done

BTW, I know in C++ using indexes can be slow, im guessing using string indexes is MUCH slower, anyone know how well

PHP

  optimizes this? Or, indeed, if it does?

Fatty

Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.

Larry Wall

thedarkness

quote author=Fatty link=topic=268.msg1809#msg1809 date=1180379542

Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.

Larry Wall


Applause

perkiset

quote author=m0nkeymafia link=topic=268.msg1805#msg1805 date=1180367961

BTW, I know in C++ using indexes can be slow, im guessing using string indexes is MUCH slower, anyone know how well

PHP

  optimizes this? Or, indeed, if it does?


All arrays in

PHP

  are associative... the [0] [1] etc elements are converted to '0' and '1' before it is processed the hashing is very fast and no issue. Arrays in

PHP

  are technically really ordered maps. Ergo there is no performance penalty for using a string rather than a numeric as an array reference. No, this is not as fast as a declared/ifed-length serial array, but they're damn fast.

/p


Perkiset's Place Home   Politics @ Perkiset's