PHP中

时间:2016-05-28 18:41:18

标签: php arrays

我想在$input之后找到放置的元素,但似乎索引的类型不是int,因此我不能对它进行数学运算。

$index = array_search($input,$tmp);
$index += 1 ;
$hold = $tmp[$index];
echo $hold; 

3 个答案:

答案 0 :(得分:0)

array_search()如果在数组中找到针,则返回针的键,否则返回FALSE。

所以你应该在假设它之前检查是否找到了某些东西。

另外,当您在索引中添加1时,检查找到的键不是数组中的最后一次出现将是一个很好的idex。

$index = array_search($input,$tmp);
if ( $index !== false && $index < count($tmp) -2 ) {
    echo $tmp[$index + 1]; 
} else {
     echo 'Not found'; 
}

答案 1 :(得分:0)

使用next()可能需要先在搜索上设置current()

答案 2 :(得分:0)

不要过度思考,只需使用array_values()

$index = array_search($input, array_values($tmp));
$index += 1;
$hold  = array_values($tmp)[$index];
echo $hold; 

您可能希望进行一些检查以确保从array_search()返回密钥并检查下一个索引isset()

$vals  = array_values($tmp);
$index = array_search($input, $vals);

if($index !== false && isset($vals[++$index])) {
    $hold = $vals[$index];  // it has already incremented with the ++$index
    echo $hold; 
}