Count the number of characters, bytes, width in PHP

How to count the number of characters, number of bytes, character width (apparent length) of a character string in PHP?

1. strlen
function strlen
Generally, to know the number of bytes, use strlen.

mb_internal_encoding('UTF-8');
$char = 'To die: to sleep No more; and by a sleep to say we end. The heart-ache and the thousand natural shocks. That flesh is heir to, tis a consummation Devoutly to be wishd. ';
echo strlen($char);

168

2. mb_strlen
function mb_strlen
Also, use mb_strlen to distinguish between full-width and half-width characters and count the number of characters.

mb_internal_encoding('UTF-8');
$char = '名前(カタカナ)';

echo mb_strlen($char);

3. mb_strwidth
function mb_strwidth
Use mb_strwidth to count character width(apparent length).

mb_internal_encoding('UTF-8');
$char = 'おはようございます。';

echo mb_strwidth($char);

Let’s put emoji and count it.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

echo strlen($char);

-> 19
it is as expected.

Then, let’s display an alert if it is more than 10 bytes.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

// echo strlen($char);
if(strlen($char) > 10){
	echo "this is more than 10 byte, please write again";
} else {
	echo "confirmed.";
}

-> this is more than 10 byte, please write again

Perfect job, am I.