php - Get first value of comma separated string

859

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?

904

Answer

Solution:

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

641

Answer

Solution:

How about

echo reset(explode(',', 'a,b,c,d'))
143

Answer

Solution:

Steve

It's little bit shorter

strtok('a,b,c,d', ",")
428

Answer

Solution:

<?php    
$array = explode(',', 'a,b,c,d');
$first = $array [0];
774

Answer

Solution:

        $int = substr($string,0,strpos($string,","));

People are also looking for solutions to the problem: php - Filter 2D associative array using keys from multiple levels of another 2D associative array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.