Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use array_search():

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

Read more: http://php.net/manual/en/function.array-search.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...