How can I get the last value after a specific delimiter in a string?
I have a string of 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 will be the last value that I would like to store in a variable.
The number can vary in size, so try:
substr($numbers, -X)
doesn't help me i guess.
How to get the number after the last comma in a line, any idea?
source to share
Just explode the string with a delimiter character and select the last token received:
<?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 am of the opinion that efficiency is less important than how easy it is to read and understand code these days. Computing power is cheap, developers are expensive. This is why I would use the first approach while waiting for the number of items in a row to get large.
source to share