开发者

PHP Set Variable to Array Key in One Line

This is going to be a very simple question, I have code that looks like this:

<?php
$rawmessage = "This is what I want.--This is all junk.";

$fmessage = explode("--", $rawmessage);
//Alt. Universe #1: $fmessage = $fmessage[0];

echo $fmessage[0]; //"This is what I want."
//Alt. Universe #1: echo $fmessage;
?>

Now I know how stupid this may sound, but is there a way I can assign $fmessage to [0] in one line? Because 1) I don't want to write $fmessage[0], it doesn't need to be an array at this point, and 2) I want to know if this is doable because this isn't the first time I've wanted to set only one part of the array to a variable. Example of what I want to write (in my fantasy land, of course. This throws an error in reality.)

<?php
$rawmessage = "This is what I want.--This is all junk.";

$fmessage = explode("--", $rawmessage)[0];
//In my fantasy land, adding the [0] means that the array's key [0] value is set to $fmessage
开发者_C百科
echo $fmessage; //"This is what I want." For real.
?>


list($fmessage) = explode('--', $rawmessage);

list() isn't a function, but a PHP language construct (or just an operator that looks like a function).

It will unpack array members into local variables...

$array = array('a', 'b', 'c');

list($a, $b, $c) = $array;

var_dump($a, $b, $c);

Outputs...

string(1) "a"
string(1) "b"
string(1) "c"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜