print key of first element of array_search() in php

106

I have following code

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

 $check_var = 'S';

i am trying to get this

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

it is returning blank value instead of "This is S"

I tried with following as well.

-> type casting of $check_var

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

but no luck. can anyone please help me to sort out this ?

Note : it works well for other values .. issue is only with first element of array .. and i am checking this on Linux

890

Answer

Solution:

Straight from the docs,Returns the key for needle if it is found in the array, FALSE otherwise. so here is where your empty string comes from.

$_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);

Works for me.

401

Answer

Solution:

Your code works,but if you are out of a class scope it should give an error..

check this fiddle

   <?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'

People are also looking for solutions to the problem: php - I want to fetch data from datetime column in this form '2015-jan-1'

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.