Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode and get a value in one line of code

Can you write the following in one line of code?

$foo = explode(":", $foo);
$foo = $foo[0];
like image 750
Emanuil Rusev Avatar asked Nov 16 '09 21:11

Emanuil Rusev


People also ask

What does the explode () function do?

The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.

What does the explode () function return?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

What is the difference between explode () Y split ()?

Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.

What would implode explode string )) do?

The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.


2 Answers

you could use stristr for this:

$foo = stristr($foo,":",true);

where true sets it to give you everything before the first instance of ":"

like image 106
GSto Avatar answered Oct 03 '22 23:10

GSto


As an alternative to list(), you may use array_shift()

$foo = array_shift(explode(':', $foo));
like image 43
qualbeen Avatar answered Oct 04 '22 00:10

qualbeen