Five PHP Functions That Would be Great in JavaScript

By Aurelio De Rosa

In one of my first articles I asserted that, while the JavaScript core continues to be improved with new methods, it still misses some useful ones. Coming from a PHP background, one of the things I really appreciate is its amazing native library. This article will discusses five PHP functions that I’d love to see in JavaScript.

Please note that this article isn’t going to assert that JavaScript is worse/better than PHP. Instead, it’s an opportunity to discuss some functions and to see how they can be implemented. Also, keep in mind that these aren’t “must have” functions, but “nice to have” ones. JavaScript continues to be a great language, even if it is missing the following utilities. For all the methods described here, I’ll add them to the prototype of the proper object so that all of the instances will share the same method.


One of the most common tasks you face when dealing with arrays is the extraction of unique values. There are different ways to achieve this goal but I’m going to show a method that tries to be as general as possible. This means that the method, using the inArray() method I showed in the previously cited article, will work if the array contains primitive values or objects.

Array.prototype.unique = function (sort, sortingFunction) {
  var array = [];
  for (var i = 0; i < this.length; i++) {
    if (array.inArray(this[i]) === false)

  if (sort === true) {
    if (typeof sortingFunction === 'function')

  return array;

The illustrated method has two parameters, the first is a Boolean to specify if the returned array must be sorted while the second is a reference to a sorting function. The returned array is initialised to an empty array, then for each array’s element, the function tests if it has been already added. If the element wasn’t already inside the array, it’ll be added. After pushing all the necessary elements, the method checks if the user wants to sort the array and also if a sorting function is given. If so, the array will be sorted using the given function, otherwise the sort() method will convert the items to strings and compare them in lexicographic order. Now that you know what the code does and because this is the most interesting method, I’ll show you three different examples.

Example 1 – Using Integers

In this example I’ll use a simple array containing numbers only. In the following two lines I’ll print the unique values and also the sorted unique values of the array.

var array = [1, 2, 9, 6, 2, 1, 9, 3];
console.log(array.unique()); // print [1, 2, 9, 6, 3]
console.log(array.unique(true)); // print [1, 2, 3, 6, 9]

Example 2 – Using Strings

This example uses an array of strings. This time, the second call to the unique() method, uses a sorting function that will help us return the array in reverse alphabetical order.

var array = ["hi", "hi", "hi", "aurelio", "hello", "aurelio", "de rosa", ""];
// print ["hi", "aurelio", "hello", "de rosa", ""]
console.log(array.unique(true, function(a, b){ return -1 * a.localeCompare(b); }));
// print ["", "hi", "hello", "de rosa", "aurelio"]

Example 3 – Using Objects

The third example uses an array of objects to demonstrate how powerful unique() is.

var array = [{x: 1, y: 2}, {x: 12, y: 3}, {x: 1, y: 2}, {x: 2, y: 3}, {x: 2, y: 4}, {x: 20, y: 23}, {x: 2, y: 3}];
// print [{x: 1, y: 2}, {x: 12, y: 3}, {x: 2, y: 3}, {x: 2, y: 3}, {x: 20, y: 23}]


In PHP you often need to print the result of an elaboration, but you have to be careful of what you’re actually injecting into your HTML code. In fact, without the proper escaping of some characters, you can allow XSS attacks. This problem can affect JavaScript code too. In PHP, to defend yourself, you can use the htmlspecialchars() function, which converts special characters like < and > into their encoded equivalent like &lt; and &gt;. This allows you to display the string without worrying about the browser interpreting it as HTML. Unfortunately, JavaScript has no equivalent native function and, for this reason, we’ll create it.

We’ll use the JavaScript native replace() method to handle this problem. What we’ll do is search for the problematic characters and replace them using the encoded equivalent entities. Since we want to change all the occurrences, we’ll use a regular expression and the g flag.

String.prototype.htmlSpecialChars = function(){
  return this
         .replace(/&/g, '&amp;')
         .replace(/</g, '&lt;')
         .replace(/>/g, '&gt;')
         .replace(/"/g, '&quot;');

Let’s see a demo that uses our htmlSpecialChars() method.

var string = 'Me, myself & I like to "code" <html>';
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;


In the previous section we saw the htmlSpecialChars() method. There are times that you want to run the inverse process, transforming the encoded string into a plain one. To achieve this goal, I’ll show you the equivalent of PHP’s htmlspecialchars_decode() function. The following is very similar to the previous so I won’t discuss it further. It simply swaps the two replace() parameters to convert from entities to the equivalent characters.

String.prototype.htmlSpecialCharsDecode = function(){
  return this
         .replace(/&amp;/g, '&')
         .replace(/&lt;/g, '<')
         .replace(/&gt;/g, '>')
         .replace(/&quot;/g, '"');

Let’s see a demo that uses our htmlSpecialCharsDecode() method.

var string = 'Me, myself & I like to "code" <html>';
// print Me, myself & I like to "code" <html>
string = string.htmlSpecialChars();
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;
string = string.htmlSpecialCharsDecode();
// print Me, myself & I like to "code" <html>


The web is full of blogs that post a lot of articles each month. Many of these blogs will uppercase every word inside the posts’ titles. Imagine that you want to apply this transformation using JavaScript. Unfortunately, JavaScript has no function like PHP’s ucwords(). But, you can easily create it by yourself. The key point of the method we’re developing is to extract and then process every word inside a string. To achieve this goal we’ll rely on the JavaScript split() method and a simple regular expression. As you may guess, we’ll split the string on spaces (not just whitespaces), uppercase the words extracted and then join them again. The code for our ucwords() method is shown below.

String.prototype.ucwords = function() {
  var words = this.split(/(s+)/);
  for(var i = 0; i < words.length; i++)
    words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length);

  return words.join('');

As you can from see reading the code, inside the for loop we’ll use the toUpperCase() method to uppercase the strings’ first character, and then concatenate the remaining characters. After that, we’ll replace the old string by reassigning the new one to its position. Now that you know how the method works, let’s see an example.

var string = 'my name is aurelio de rosa';
// print My Name Is Aurelio De Rosa


From the code of ucwords(), we can extract an idea for another similar PHP function – ucfirst(). The latter makes a string’s first character uppercase. What differs from the ucwords() implementation, is that we don’t need a loop to iterate over the words but we can split, convert only the first word, and then join. The source of ucfirst() is shown below.

String.prototype.ucfirst = function() {
  var words = this.split(/(s+)/);
  if (words[0] != null)
     words[0] = words[0][0].toUpperCase() + words[0].substr(1, words[0].length);

  return words.join('');

An example use of this function is illustrated below.

var string = 'my name is aurelio de rosa';
// print My name is aurelio de rosa


Although JavaScript’s core continues to evolve with every release, there are several functions missing. However, you can find many of them in your framework of choice like jQuery. If you prefer to use raw JavaScript, or just need few functions, this article showed you how easy it is to write your own implementations. As a final note, I want to highlight that all the methods I described have been added to the prototype of their respective type – unique() to the Array prototype, and htmlSpecialChars(), htmlSpecialCharsDecode(), ucwords(), and ucfirst() to the String prototype. This allows all variables of that type to share the same code.

  • Jon Hartmann

    Great ideas, and I like that you choose to extend the base objects, but you’ll always want checks for existence before doing that. Also, I know you were choosing to use PHP style names, but something like toProperCase() instead of ucwords() would better match existing syntax.

    • Glad that you find the article useful. Your suggestion about naming is good and you understand well why I called the functions the way I did. Of course rename a function is very easy so who wants can do it.

  • Ben Barber

    Hey, Aurelio! Thanks for this write-up!

    I’d caution against adding these methods to the .prototype property. MooTools just ran into an issue where they had to patch an old version of their library because String.prototype.contains got standardized in ECMAScript 6 with a conflicting implementation. I think the Array.prototype.unique method is the most at risk of something like that.

    • You’re absolutely right about the check if a native implementation exists. I thought about that while writing the article but in the end I decided to not include them. But you were right to said it.

  • Patrick

    In PHP, htmlentities() replaces *all* characters for which there is an entity code with their HTML entity. hmtlspecialchars() replaces the less than and greater than, ampersand, and double and single quote characters to their respective HTML entities. For consistency with this naming, I’d recommend changing the name of your htmlEntities() function (and the decode function) to htmlSpecialChars().

    • You’re right saying that it could be misleading. I changed the titles.

      • sachin

        Yes you are saying is correct.

  • Ron

    Check out
    Here you’ll find many PHP methods implemented in JavaScript.

    • Hi Ron. Thank you the link, however I already know that site. Moreover, the point here isn’t to simply create PHP functions in JS but have a point of discussion to allow beginner to think and learn something new.

  • kAlmAcetA

    great resource about this topic at, almost every function from PHP that could be implemented in JS is there.

  • jayshree


  • Your ucfirst function could be written in a single line, no need to do any of that split stuff:

    return this.charAt(0).toUpperCase() + this.substr(1);

    However I still think that prototyping native methods is a bad idea, because it breaks the principle of encapsulation. We go out of our way to avoid creating too many global variables, because they pollute the global scope and might affect other scripts. Binding prototypes to native objects is exactly the same.

Get the latest in JavaScript, once a week, for free.