Get the index value of an array in PHP

后端 未结 12 2014
迷失自我
迷失自我 2020-12-04 23:05

I have an array:

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

I want to get the index for a given value (i.e. 1 for <

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 23:44

    You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

     'boring',
    'Friday' => 'yay',
    'boring',
    'Sunday' => 'fun',
    7 => 'boring',
    'Saturday' => 'yay fun',
    'Wednesday' => 'boring',
    'my life' => 'boring');
    
    $repeating_value = "boring";
    
    function array_value_positions($array, $value){
        $index = 0;
        $value_array = array();
            foreach($array as $v){
                if($value == $v){
                    $value_array[$index] = $value;
                }
            $index++;
            }
        return $value_array;
    }
    
    $value_array = array_value_positions($given_array, $repeating_value);
    
    $result = "The value '$value_array[0]' was found at these indices in the given array: ";
    
    $key_string = implode(', ',array_keys($value_array));
    
    echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7
    
    

提交回复
热议问题