Assign array element to variable in PHP

2019-03-02 11:16发布

I know this is a silly question, but i'm stucked! I have the following array:

Array ( [type] => 8 [message] => Use of undefined constant hola - assumed 'hola' 
 [file] => C:\wamp\www\WeCode\code.php(29) : eval()'d code [line] => 3 ) 

I want a variable $var to have the string of [message] element. I'm trying to access the array via indexes, but it throws me offset errors! So what can I do? I think is pretty simple, but I'm stuck with that.

3条回答
聊天终结者
2楼-- · 2019-03-02 11:47

It's an associative array and you need to access elements by key. In your case:

$var = $array['message'];
查看更多
女痞
3楼-- · 2019-03-02 11:55

I believe your array syntax is correct, but I like to create associative arrays this way:

$array1 = array( 'type' => 8, 'message' => "Use of undefined constant hola - assumed 'hola'", 'file' => "C:\wamp\www\WeCode\code.php(29) : eval()'d code", 'line' => 3 );

Then since this is an associative array, you can access it like this:

$var2 = $array1['message'];
查看更多
唯我独甜
4楼-- · 2019-03-02 12:00

You can use:

$var = $array['message'];

In this case, message is your array index.

查看更多
登录 后发表回答