Nov 4

Have you ever wanted to get the key name AND the value of an array for use in a loop? You might have done something like this (I know I have):

$keys = array_flip($array);
foreach($array as $a){
	echo($keys[$a] . "-" . $a . "\\n");
}

Why is this bad? It uses almost twice as much memory as this next method. The following will produce the same output as the above with less code and less memory:

foreach($array as $k=>$v){
	echo($k . "-" . $v . "\\n");
}

Essentially, this second method just takes the key and the value and assigns them through each iteration through the loop, rather than having to go through each index in two separate arrays. Hope this is useful to someone (it was to me) :)

  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.