PHP list quick tip

Written by on April 14, 2010 in General - 2 Comments

It often happens that i use some function or method that returns an array of elements, but i need just the first one. Assigning this first element to variable is usually done in two lines, for example:

$arr = explode(".", "zxc.vbn.asd");
$first = $arr[0];
// $first = "zxc"

With the help of function list() it can be narrowed down to just one line:

list($first) = explode(".", "zxc.vbn.asd");
// $first = "zxc"

In my opinion that’s a neat solution for common problem, saves just a one line (and some memory), yet judging by the number of times we do “such thing” in the project i think you will find this helpful.

About the Author

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

2 Comments on "PHP list quick tip"

  1. Fadlee April 18, 2010 at 4:15 pm ·

    You can use strtok function for this purpose.

    Example:

    $first = strtok( “zxc.vbn.asd” , “.” );

  2. Greg April 20, 2010 at 4:02 pm ·

    Yes, but only in this example.

Leave a Comment