Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first value of comma separated string

Tags:

arrays

php

I'm looking for the quickest/shortest way to get the first value from comma separated string, in-line.

The best I can do is

$string = 'a,b,c,d';
echo "The first thing is " . end(array_reverse(explode(',', $string))) . ".";

but I feel that's excessive and redundant. Is there a better way?

like image 813
Steve Robbins Avatar asked May 10 '12 19:05

Steve Robbins


2 Answers

list($first) = explode(',', 'a,b,c,d');
var_dump($first);  // a

probably works :)


In PHP 6.0 you will be able to simply:

$first = explode(',', 'a,b,c,d')[0];

But this is a syntax error in 5.x and lower

like image 58
Halcyon Avatar answered Sep 26 '22 20:09

Halcyon


How about

echo reset(explode(',', 'a,b,c,d'))
like image 28
itsmeee Avatar answered Sep 23 '22 20:09

itsmeee