explode function and array element reading [duplicate]
Possible Duplicate:
php explode and array index
I am new to PHP and would like to ask if there is a way to write a php code like
$lengthofstay = ($duration <= 0 ? 'optional' : explode("_", $duration )[0]);
i mean calling the explode function and at the sametime reading the first ele开发者_运维技巧ment of resulting array.
it would be possible in 5.4
but your code is as ugly as hell.
there is nothing good in writing all the code in one line.
Write in in three lines and when you come across it in a week, you wouldn't stumble upon it, puzzled.
if ($duration <= 0)
$lengthofstay = 'optional';
} else {
list($lengthofstay) = explode("_", $duration, 1);
}
nothing wrong with it.
if you want to make it strictly one-liner - create a function. and then call it
$lengthofstay = get_length_of_stay($duration);
it's shorter than your cunning construct and way more readable
You might want to use the limit-parameter from explode:
explode("_", $duration, 1)
精彩评论