The JavaScript String charCodeAt() function returns the Unicode value of the character at the specified index in a string. The index is zero-based, meaning the first character in the string has an index of 0, the second character has an index of 1, and so on. The returned value is an integer between 0 and 65535, representing the Unicode value of the character. If the specified index is out of range, the function returns NaN (Not a Number). This function is useful for working with strings that contain non-ASCII characters, as it allows you to access the Unicode values of those characters. Keep reading below to learn how to Javascript String charCodeAt in PHP.

Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!

Buy Now On Amazon

Javascript String charCodeAt in PHP With Example Code

JavaScript’s `charCodeAt()` method is used to return the Unicode value of the character at a specified index in a string. In PHP, we can achieve the same functionality using the `mb_ord()` function.

The `mb_ord()` function returns the Unicode code point value of a specified character. It is similar to the `ord()` function in PHP, but it supports multi-byte characters.

Here’s an example of how to use `mb_ord()` to get the Unicode value of a character at a specific index in a string:


$string = "Hello, world!";
$index = 1;
$unicodeValue = mb_ord($string[$index], 'UTF-8');
echo $unicodeValue; // Output: 101

In this example, we’re getting the Unicode value of the character at index 1 in the string “Hello, world!”. The `mb_ord()` function takes two parameters: the character to get the Unicode value of, and the character encoding of the string (in this case, UTF-8).

We can use this function to replicate the functionality of JavaScript’s `charCodeAt()` method in PHP.

Equivalent of Javascript String charCodeAt in PHP

In conclusion, the charCodeAt() function in JavaScript is a useful tool for retrieving the Unicode value of a character in a string. In PHP, the equivalent function is ord(), which returns the ASCII value of a character. While the two functions have different outputs, they serve the same purpose of providing a numerical representation of a character. It’s important to note that Unicode and ASCII values are not the same, so it’s important to use the appropriate function depending on the encoding of your string. Overall, understanding the charCodeAt() function in JavaScript and its equivalent in PHP can help developers manipulate strings more effectively in their code.

Contact Us