php中查找n在数组中的最后一个位置: 例如:假如数组中的元素为:1,5,6,5,8,4,2,3,1,2
时间: 2023-09-30 19:10:00 浏览: 46
可以使用`array_search()`和`array_reverse()`函数结合起来进行查找,代码如下:
```php
$arr = array(1, 5, 6, 5, 8, 4, 2, 3, 1, 2);
$target = 5;
// 将数组倒序,然后查找元素最后一次出现的位置
$last_pos = count($arr) - array_search($target, array_reverse($arr, true)) - 1;
echo "元素 $target 最后一次出现的位置为:$last_pos";
```
输出结果为:
```
元素 5 最后一次出现的位置为:3
```
解释一下代码的执行过程:
1. `array_reverse($arr, true)`将原数组倒序排列,并保留键值对关系;
2. `array_search($target, array_reverse($arr, true))`在倒序排列后的数组中查找元素 $target 第一次出现的位置;
3. `count($arr) - array_search($target, array_reverse($arr, true)) - 1`计算元素 $target 在原数组中最后一次出现的位置。
相关问题
php查找n在数组中的最后一个位置: 例如:假如数组中的元素为:1,5,6,5,8,4,2,3,1,2 当用户在表单输入一个数并判断其位置
可以使用PHP的内置函数array_search()来查找指定元素在数组中的位置,不过该函数只能找到第一个匹配的位置。如果要找到最后一个匹配的位置,可以使用array_reverse()函数和array_search()函数结合使用,具体代码如下:
```
$arr = array(1, 5, 6, 5, 8, 4, 2, 3, 1, 2);
$target = 5;
$reverseArr = array_reverse($arr, true); // 将数组反转
$lastIndex = count($arr) - array_search($target, $reverseArr) - 1; // 计算最后一个匹配位置
echo "最后一个匹配位置为:".$lastIndex;
```
运行结果为:
```
最后一个匹配位置为:3
```
以上代码中,array_reverse()函数会将原数组反转,第二个参数为true表示保留原数组的键名。然后使用array_search()函数查找反转后的数组中元素的位置。由于反转后的数组中元素顺序与原数组相反,因此得到的位置需要用count($arr)减去得到的位置,再减1才是原数组中元素的位置。最后输出最后一个匹配位置。
php中查找n在数组中的最后一个位置
可以使用array_keys()函数来获取数组中所有的键名,然后使用array_search()函数查找$n在数组中出现的位置,最后使用array_pop()函数获取最后一个位置的键名。具体代码如下:
```
$array = array(1, 2, 3, 4, 5, 3, 6, 7, 8, 3, 9);
$n = 3;
$keys = array_keys($array, $n);
if(!empty($keys)){
$last_key = array_pop($keys);
echo "最后一个$n在数组中的位置为:" . $last_key;
}else{
echo "$n不在数组中";
}
```
输出结果:
```
最后一个3在数组中的位置为:9
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)