Filip Blaauw
Filip Blaauw

Reputation: 761

Get the last value in a comma-separated string

I have a string with numbers, stored in $numbers:

3,6,86,34,43,52

What's the easiest way to get the last value after the last comma? In this case the number 52 would be the last value, which I would like to store in a variable.

The number can vary in size, so trying:

substr($numbers, -X)

does not help me out I think.

Upvotes: 4

Views: 4855

Answers (5)

mickmackusa
mickmackusa

Reputation: 47904

A direct, single-function approach would be to trim every upto the last comma.

Code: (Demo)

$numbers = "3,6,86,34,43,52";
echo preg_replace('/.*,/', '', $numbers);
// 52

Upvotes: 0

Mureinik
Mureinik

Reputation: 311468

I'd just explode it to an array, and get the last element:

$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];

Upvotes: 0

Rizier123
Rizier123

Reputation: 59691

This should work for you:

Just use strrpos() to get the position of the last comma and then use substr() to get the string after the last comma, e.g.

$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);

output:

52

Upvotes: 6

NorthernLights
NorthernLights

Reputation: 370

You can do it like this:

$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);

echo $arr[count($arr)-1];

Upvotes: 0

arkascha
arkascha

Reputation: 42925

Just explode the string by the separator character and pick the last of the resulting tokens:

<?php
$string = '3,6,86,34,43,52'; 
$tokens = explode(',', $string);
echo end($tokens);

An alternative would be to use a regular expression:

<?php
$string = '3,6,86,34,43,52'; 
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);

Personally I have the opinion that efficiency is less important that easy of reading and understanding the code these days. Computation power is cheap, developers are expensive. That is why I would use the first approach, expect when the number of elements in the string gets big.

Upvotes: 0

Related Questions