Vérification lors de l'itération du tableau, si l'élément courant est le dernier élément
Aidez-moi à traduire ce pseudo-code en vrai code php:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
Edit: le tableau peut avoir des clés numériques ou de chaîne
8 réponses
Vous pouvez utiliser la fin de PHP ()
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
Update1
Comme indiqué par @Mijoja, ce qui précède pourrait avoir un problème si vous avez la même valeur plusieurs fois dans le tableau. ci-dessous est la solution pour elle.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
if($k == $lastElementKey) {
//during array iteration this condition states the last element.
}
}
Update2
J'ai trouvé la solution par @onteria_ pour être meilleure que ce que j'ai répondu car elle ne modifie pas le pointeur interne des tableaux, je mets à jour la réponse pour correspondre à sa réponse.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
if($k == $lastArrayKey) {
//during array iteration this condition states the last element.
}
}
Merci @onteria_
Cela fait toujours l'affaire pour moi
foreach($array as $key => $value) {
if (end(array_keys($array)) == $key)
// Last key reached
}
Modifier 30/04/15
$last_key = end(array_keys($array));
reset($array);
foreach($array as $key => $value) {
if ( $key == $last_key)
// Last key reached
}
Pour éviter L'avertissement E_STRICT mentionné par @ Warren Sergent
$array_keys = array_keys($array);
$last_key = end($array_keys);
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Depuis array_pop
fonctionne sur le tableau temporaire créé par array_keys
, il ne modifie pas le tableau d'origine à tous.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
Je sais que c'est vieux, et en utilisant l'itérateur SPL peut-être juste un excès, mais de toute façon, une autre solution ici:
$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
// just to use this `hasNext()` method to see
// if this is the last element
echo $each;
}
}
Ma solution, aussi assez simple..
$array = [...];
$last = count($array) - 1;
foreach($array as $index => $value)
{
if($index == $last)
// this is last array
else
// this is not last array
}
Pourquoi pas cette méthode très simple:
$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
$i++;
if( $i == sizeof($array) ){
//we are at the last element of the array
}
}
Si les éléments sont classés numériquement, utilisez la fonction key() pour déterminer l'index de l'élément courant et le comparer à la longueur. Vous devrez utiliser next () ou prev () pour faire défiler les éléments dans une boucle while au lieu d'une boucle for:
$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
$v = current($arr); doSomething($v); //do something if not the last item
next($myArray); //set pointer to next item
}
$arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
foreach ($arr as $key => $val) {
echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
}
// output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1