http://Bj83.de

key von array eintrag in foreach schleife

mit hilfe einer zusatzfunktion
function KeyName(array $a, $pos) {
$temp = array_slice($a, $pos, 1, true);
return key($temp);
}

und eines zaehlers…

Ein Beispiel mit Ausgabe:

<?php
$arr1 = array('test'=>'', 'test2'=>'');
$arr2 = array('test'=>' ', 'test2'=>' ');

var_dump($arr1);
var_dump($arr2);

echo count($arr1) .' - '. count($arr2) .'<br>'; 

echo '<br><b>arr1 with current-next</b><br>';
while($dummy = current($arr1)){
    echo key($arr1).' - "'.$dummy.'"<br>';
	next($arr1);
}

echo '<br><b>arr1 with current-next</b><br>';
while($dummy = key($arr1)){
	echo key($arr1).' - "'.$dummy.'"<br>';
	next($arr1);
}

echo '<br><b>arr1 v2 with foreach</b><br>';
foreach($arr1 as $entry){
	echo key($arr1).' - "'.$entry.'"<br>';
}

echo '<br><b>arr1 v3 with foreach and key function</b><br>';
$c1 = 0;
foreach($arr1 as $entry){
	echo KeyName($arr1,$c1).' - "'.$entry.'"<br>';
	$c1++;
}

echo '<br><b>arr2 with current-next</b><br>';
while($dummy = current($arr2)){
	echo key($arr2).' - "'.$dummy.'"<br>';
	next($arr2);
}

echo '<br><b>arr2 v2 with foreach</b><br>';
foreach($arr2 as $entry){
	echo key($arr2).' - "'.$entry.'"<br>';
}

echo '<br><b>arr2 v3 with foreach and key function</b><br>';
$c1 = 0;
foreach($arr2 as $entry){
	echo KeyName($arr2,$c1).' - "'.$entry.'"<br>';
	$c1++;
}

function KeyName(array $a, $pos) {
    $temp = array_slice($a, $pos, 1, true);
    return key($temp);
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers: