dourun2990
dourun2990
采纳率100%
2017-06-13 06:41

Php获取数组中所有项的键,其中value等于特定常量

已采纳

I have an array like the one below:

$v = array(1,2,3,4,2,3);

How do I get the keys of all elements in array where the value is equal to 2?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duanmei2805 duanmei2805 4年前

    If you have a value in an array and you want to get the keys you can use array_keys() with the optional search_value:

    $v = array(1,2,3,4,2,3);
    $keys = array_keys($v, '2');
    print_r($keys);
    
    // Array
    // (
    //    [0] => 1
    //    [1] => 4
    // )
    

    For the output check https://3v4l.org/N8EBH

    点赞 评论 复制链接分享
  • dongping5230 dongping5230 4年前

    Try this code

    $v = array(1,2,3,4,2,3);
    $a = 2;
    
    $key = array();
    foreach($v as $k=>$val)
    {
        if($a == $val)
        {
            $key[] = $k;
        }
    }
    
    print_r($key);
    
    点赞 评论 复制链接分享
  • dougu5950 dougu5950 4年前

    You can do it like

    <?php
    $v = array(1,2,3,4,2,3);
    $keys = array();
    foreach($v as $k=>$x)
    {
      if($x == 2) 
        $keys[] = $k;
    }
    echo "<pre>";print_r($keys);echo "</pre>";
    
    点赞 评论 复制链接分享

相关推荐