If this were an array rather than a string you would use array_pop, So I would create a function called string_pop() and add it to my list of helpers.
It would mimic array_pop function but for string.
array_pop works like this
function array_pop(array &$array){ $last_value = end($array); $last_key = key($array); unset($array[$last_key]); reset($array); return $last_value; }
So string_pop would look like this
function string_pop(&$str){ $last_char = substr($str, -1); $str = substr($str, 0, -1); return $last_char; }
All you have to do now is put the returned value and the original variable in an array or create a function to do this for you string_pop_array().
function string_pop_array($str) { $last_char = string_pop($str); return array($str, $last_char); } $var = '12345E'; print_r(string_pop_array($var); Array ( [0] => 12345 [1] => E )
Using string_pop() will alter the variable passed to it ($str), this is because it is passed by reference , but by calling the string_pop_array() function the original string ($var) wont be effected, only the $str variable within the functions scope will change.
Just to tie up loose ends here's the equivalent function for an array.
function array_pop_array($arr) { $last_element = array_pop($arr); return array($arr, $last_element); } $arr = array(1,2,3,4,5,'E'); print_r(array_pop_array($arr); Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) [1] => E )
and the string equivalent to array_shift
function string_shift(&$str){ $first_char = substr($str, 0, 1); $str = substr($str, 1); return $first_char; }
DEMO