JavaQueen JavaQueen - 4 years ago 77
PHP Question

get a value by the key from an array

I have a static class

, where I defined a method
to retrieve a variable : array with keys and values:

private $Msg = array()

public static function getMsg()
return $this->Msg;

Then I use this variable as follows in another class :

Tools::getMsg()['key'] = $this->message;

My question, I want to get the value by providing the key. I know about the php function

array_search — Searches the array for a given value and returns the
first corresponding key if successful

But is there a function to search the array for a given key ?
I don't know if the syntax of my code above is correct so, if not I may need to use a function.

Here is an example of the Msg array :

$Msg = array('Class1' => 'File does not exist',
'Class2' => 'Error in timestamp format')

Answer Source

To access an array, you do not need to use a built-in function. Simply access the array as follows.

$arr = array('foo' => 42, 'bar' => 'rab', 'baz' => false); // example array
echo $arr['bar']; // will output 'rab'
$key = 'foo';
echo $arr[$key]; // will output 42

As a sidenote: you cannot use $this in a static context. Use self::$Msg and declare $Msg as private static $Msg, or make the access not static at all. Your code could be along the following lines.

private static $Msg = array();

public static function getMsg()
    return self::$Msg;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download