Filip Blaauw
Filip Blaauw

Reputation: 761

Get the last value in comma separated string

I have this string: 24.045,25.531,26.890 as php variable $numbers

How can i echo the number after the last comma (in this case 26.890)? The number can vary in size, e.g. 9.04 or 120.34521. So I need to set the last comma as my starting point.

Can I search for the last comma, and echo whatever that is behind it?

Upvotes: 1

Views: 8378

Answers (2)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use explode to split the numbers into an array and end to get the last item of the array:

$numbers = '24.045,25.531,26.890';
$numbers = explode(',', $numbers);
$lastNumber = end($numbers);

demo: https://ideone.com/VDppCP

Upvotes: 8

Shira
Shira

Reputation: 6560

Without creating a temporary array with all of the numbers (which you might not need):

echo substr($numbers, strrpos($numbers, ',') + 1);

And if you need to handle strings that might not contain a comma at all:

echo substr(
    $numbers,
    ($lastCommaPos = strrpos($numbers, ',')) !== false ? $lastCommaPos + 1 : 0
);

Upvotes: 5

Related Questions