这仅适用于具有索引号的数组.例如,我有这个数组;
$array = [
"0" => "number 1",
"1" => "number 2",
"2" => "number 3",
"3" => "number 4",
"4" => "number 5",
"5" => "number 6",
"6" => "number 7",
"7" => "number 8",
"8" => "number 9"
];
我想跳过某些特定范围的关键索引,例如,如果索引的数量从0到5,则跳过foreach.这意味着我们可以这样做.
foreach($array as $key => $value){
if(array_key_exist($key, range(0,5))
continue;
echo $value."
"
}
或者我们可以使用for …循环
for($ind = 0; $ind < count($array); $ind++){
if(array_key_exist($ind, range(0,5))
continue;
echo $arr[$ind]."
"
}
我如何不使用继续或先搜索array_key而跳过索引?确保上面的代码对我来说很好,但是如果我有一堆数组键和值,我认为这不是一个好选择.
解决方法:
您可以从第5个索引开始获取数组的切片,再到其余部分,
$result = array_slice($array,5,count($array)-5, true);
Note:
array_slice() will reorder and reset the integer array indices by
default. This behaviour can be changed by setting preserve_keys to
TRUE. String keys are always preserved, regardless of this parameter.
标签:for-loop,foreach,arrays,php
来源: https://codeday.me/bug/20191210/2104801.html