Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode and array index

Tags:

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];

like image 872
kusanagi Avatar asked Jan 09 '11 13:01

kusanagi


People also ask

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

What is the difference between explode () and split () functions in PHP?

Both the functions are used to Split a string. However, Split is used to split a string using a regular expression. On the other hand, Explode is used to split a string using another string.

What is difference between implode and explode in PHP?

PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array.


2 Answers

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]; 
like image 120
Bailey Parker Avatar answered Sep 26 '22 06:09

Bailey Parker


You are correct with your second code-block. explode, and other functions can't return a fully formed array for immediate use,and so you have to set a temporary variable. There may be code in the development tree to do that, but the only way to get the elements you need for now, is the temporary variable.

like image 24
Alister Bulman Avatar answered Sep 25 '22 06:09

Alister Bulman