PHP数组中值出现的第一个和最后一个索引 [英] First and Last Index of occurrence of value in PHP Array

查看:215
本文介绍了PHP数组中值出现的第一个和最后一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中创建了一个数组,如下所示:

I have an array created in PHP as follows:

$ arr = array(123,144,144,123);

如何获取每个值出现的第一个和最后一个索引。

类似,

How do I get the first and last indexes of occurrence of each value.
Something like,

123 -> first occurrence - 0th index | last occurrence - 3rd index
144 -> first occurrence - 1st index | last occurrence - 2nd index


推荐答案

使用 array_search()

$arr = array(123,144,144,123);
$first = array_search(123, $arr); // 0
$last = array_search(123, array_reverse($arr, true)); // 3

了解更多: http://php.net/manual/zh/function.array-search.php

这篇关于PHP数组中值出现的第一个和最后一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆