2011-05-23 107 views
50

請幫我翻譯這個僞代碼,以真正的PHP代碼:檢查,如果當前元素爲最後一個元素

foreach ($arr as $k => $v) 
    if (THIS IS NOT THE LAST ELEMENT IN THE ARRAY) 
     doSomething(); 

編輯:數組可以具有數字或字符串鍵

+5

爲什麼不對'count($ arr) - 1'迭代使用'for'循環? – Marcin 2011-05-23 01:44:36

+0

如果你有混合鍵,你如何確定哪個鍵是最後一項?如果您希望它作爲添加到數組中的最後一項,則應該有一些數據來指示時間戳。 – Rasika 2011-05-23 01:53:14

+0

last的定義:由數組的內部順序決定。這與說foreach循環選擇的最後一個元素相同 – shealtiel 2011-05-23 02:32:32

回答

88

您可以使用PHP的end()

$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

正如@Mijoja指出的那樣,如果在數組中有多次相同的值,那麼上面的代碼可能會有問題。下面是它的修復。

$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

我找到解決方案通過@onteria_會更好然後什麼我已經回答了,因爲它不修改數組內部指針,我更新的答案,以配合他的回答。

$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. 
    } 
} 

謝謝@onteria_

+9

如果您在數組中有多次相同的值 – Mijoja 2012-04-10 19:51:11

+2

謝謝@Mijoja指出,這將會出現問題。更新了代碼:) – 2012-04-11 07:16:01

11
$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"; 
    } 
} 

由於array_poparray_keys創建的臨時陣列上的作品不修改原始數組的。

$ php test.php 
test1 -> foo 
test2 -> bar 
test3 -> baz 
0 -> foo 
1 -> bar 
2 -> baz 
+0

我比接受的答案更喜歡這個,因爲它只需要一行用於循環外的初始化。 – 2012-12-11 17:27:46

+0

我喜歡這個比接受的答案更好,因爲它不會改變你要循環的數組的內部指針。 – autonymous 2013-07-01 18:03:03

+0

對第一個元素'$ first = array_shift(array_keys($ myarray2));' – Luke 2014-05-27 06:23:37

0

如果項目按數字排序,則使用key()函數確定當前項目的索引並將其與長度進行比較。你必須通過的項目在一個while循環使用的next()或prev()循環,而不是一個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 
} 
+0

因爲這是我在Google搜索時發現的第一件事。瞭解所有不同的方法來做同樣的事情,並且更好地精通是很好的。 :D – trusktr 2011-05-23 02:13:35

+1

不適用於非數字或非嚴格訂購的項目 – shealtiel 2011-05-23 02:35:37

+0

呃,是的。感謝您指出了這一點! – trusktr 2011-05-26 04:16:44

0
$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 
14

這永遠不會把戲對我來說

foreach($array as $key => $value) { 
    if (end(array_keys($array)) == $key) 
     // Last key reached 
} 

編輯30/04/15

$last_key = end(array_keys($array)); 
reset($array); 

foreach($array as $key => $value) { 
    if ($key == $last_key) 
     // Last key reached 
} 

爲了避免@Warren塞爾讓

提到E_STRICT警告0
$array_keys = array_keys($array); 
$last_key = end($array_keys); 
+0

更優雅,更輕鬆! :) – 2014-11-25 18:02:49

+0

我不知道爲什麼這個評論不是被接受的答案。對於絕大多數潛在用例(即關聯的**和**枚舉數組),所有提供的答案和工作都是最簡單/最乾淨的。 – Pierce 2015-01-30 01:16:52

+1

@Pierce給你一個提示:這是在接受答案後的3年半回答,再加上如果你的數組中有1000個項目,你將調用「結束」1000次和「array_keys」1000次。 – StefanNch 2015-04-10 15:38:19

1

我的解決辦法,也很簡單..

$array = [...]; 
$last = count($array) - 1; 

foreach($array as $index => $value) 
{ 
    if($index == $last) 
     // this is last array 
    else 
     // this is not last array 
} 
1

我這裏知道這是舊的,並且使用SPL迭代器也許只是一個矯枉過正,但無論如何,另一種解決方案:

$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; 
    } 
} 
0

爲什麼不用這個非常簡單的方法:

$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 
    } 
} 
相關問題