在 PHP 中 array_search() 的第一个元素的打印键


print key of first element of array_search() in php

我有以下代码

 public static $_myarray = array('This is S' => 'S',
                          'This is RC' => 'RC',
                          'This is RF' => 'RF',
                          'This is C' => 'C');
 $check_var = 'S';

我正在尝试得到这个

echo $key_of_array =  array_search($check_var,$_myarray); // output should be 'This is S'

它返回空白值而不是"这是 S"

我也尝试了以下方法。

->型铸造$check_var

-> array_search($check_var,$_myarray,true);

但没有运气。 谁能帮我解决这个问题?

注意:它适用于其他值..问题仅适用于数组的第一个元素..,我正在Linux上检查这一点

直接来自文档,Returns the key for needle if it is found in the array, FALSE otherwise.所以这就是你的空字符串的来源。

$_myarray = [
    'This is S' => 'S',
    'This is RC' => 'RC',
    'This is RF' => 'RF',
    'This is C' => 'C'
];
$check_var = 'S';
echo array_search($check_var,$_myarray);
echo array_search('S',$_myarray);

为我工作。

你的代码可以工作,但如果你不在类范围之内,它应该会给出一个错误。

检查这个小提琴

   <?php
    //echo phpinfo();
    /*public*/ $_myarray = array('This is S' => 'S', //note that public keyword causes an error out of class scope..
                              'This is RC' => 'RC',
                              'This is RF' => 'RF',
                              'This is C' => 'C');
    $check_var = 'S';
    echo $key_of_array =  array_search($check_var,$_myarray); // output should be 'This is S'