PHP获取数组中某个值的索引 [英] Get the index of a certain value in an array in PHP

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

问题描述

我有一个数组:

$list = array('string1', 'string2', 'string3');

我想获取给定值的索引(即 1 用于 string22 用于 string3)

I want to get the index for a given value (i.e. 1 for string2 and 2 for string3)

我想要的是字符串在数组中的位置

All I want is the position of the strings in the array

  • string1 为 0
  • string2 是 1
  • string3 是 2

如何实现这一目标?

推荐答案

array_search 是解决方案.

array_search (混合 $needle , 数组 $haystack [, bool $strict = FALSE ] ) : 混合

来自文档:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

您可以手动遍历数组并找到索引,但是当有一个函数时为什么要这样做.这个函数总是返回一个键,它可以很好地处理关联数组和普通数组.

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

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

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