A PHP last character function

PHP string FAQ: Can you share some source code for a PHP last character function (string function)?

Sure, I just developed a PHP last character function for an app I'm working on, and here's the source code for that function, aptly named last_char:

# a php last character function
function last_char($str)
{
  $len = strlen($str);
  return char_at($str, $len-1);
}

As you can tell from the code, it returns the last character from a PHP string.

Oops, I see it requires my PHP char_at function. Here's the source code for it as well:

function char_at($str, $pos)
{
  return $str{$pos};
}

Of course if you're a PHP whiz you can knock out this PHP last character functionality in just one or two lines of code, but I happen to like a lot of small functions that do one thing, hence this breakdown.

This PHP last character function isn't too amazing or anything like this, but hopefully it is useful. :)

 

Comments

I had a vague memory while reading this post of being able to get the last character(s) in a string using negative parameters for the substr function, and indeed you can:

http://uk.php.net/manual/en/function.substr.php

So you could do

function last_char($str)
{
return substr($str, -1);
}

Personally, I would opt to put the substr call in my code, rather than call a special last_char function, because it becomes transparent what is actually being done, so if I was actually getting the last 2 chars I would modify the line to be substr($mystr, -2) rather than calling last_char twice. It also saves an assignment (with associated type checking) and a function call. Remember the built-in function will always be far more efficient than PHP code.