phparraysreturn-value

Directly access element by index from explode()'s returned array


How can I get the following code to work?

$a = explode('s', $str)[0];

I only see solutions looking like this:

$a = explode('s', $str);
$a = $a[0];

Solution

  • As others have said, PHP is unlike JavaScript in that it can't access array elements from function returns. The second method you listed works. You can also grab the first element of the array with the current(), reset(), or array_pop() functions like so:

    $a = current( explode( 's', $str ) ); //or
    $a = reset( explode( 's', $str ) ); //or
    $a = array_pop ( explode( 's', $str ) );
    

    If you would like to remove the slight overhead that explode may cause due to multiple separations, you can set its limit to 2 by passing two after the other arguments. You may also consider using str_pos and strstr instead:

    $a = substr( $str, 0, strpos( $str, 's' ) );
    

    Any of these choices will work.

    EDIT Another way would be to use list() (see PHP doc). With it you can grab any element:

    list( $first ) = explode( 's', $str ); //First
    list( ,$second ) = explode( 's', $str ); //Second
    list( ,,$third ) = explode( 's', $str ); //Third
    //etc.
    

    That not your style? You can always write a small helper function to grab elements from functions that return arrays:

    function array_grab( $arr, $key ) { return( $arr[$key] ); }
    
    $part = array_grab( explode( 's', $str ), 0 ); //Usage: 1st element, etc.
    

    EDIT: PHP 5.4 will support array dereferencing, so you will be able to do:

    $first_element = explode(',','A,B,C')[0];