2

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

echo $fmessage; //"This is what I want." For real.
?>
5
  • 1
    Your fantasy land array dereferencing actually works with the latest code in the PHP trunk, so maybe that feature will show up in PHP 5.4. Commented Dec 7, 2010 at 5:53
  • @konorce About friggin' time! Commented Dec 7, 2010 at 5:54
  • Say wha? I should be a PHP developer if I'm thinking that ahead! :P Commented Dec 7, 2010 at 5:55
  • 1
    You can only be a PHP dev if you consider using a :) for a namespace separator :P Commented Dec 7, 2010 at 5:56
  • @alex I had to think real hard to make up the --! And also, bit.ly/bBwlZw Commented Dec 7, 2010 at 6:03

1 Answer 1

4
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"
Sign up to request clarification or add additional context in comments.

3 Comments

You're too damn quick! ;-) +1
That was incredibly fast O_O. Just so I'm clear though, should I be expecting a visit from the PHP developers and receive a slap on the wrist for bad practice or is this A-OH-KAY?
@NessDan This is fine, so long as you don't abuse it. Basically this is a terser version of your posted code, with the same result at the end, so that is OK.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.