Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use strtolower() rather than mb_strtolower()?

Tags:

php

I understand the usage/behaviour difference between strtolower() and mb_strtolower() functions. And it has been asked before :)

But I don't understand - what is the current purpose of strtolower?

Is it available because of backwards compatibility? Or is there some use cases when strtolower is preferable? It seems that mb_strtolower() is safer and more versatile so I am tempted to use it everywhere...

like image 727
Džuris Avatar asked Sep 19 '16 15:09

Džuris


2 Answers

Not really backward compatibility, but the ability to use code wihtout additionally loaded multibyte string extension. So a question of portability of the code.

strtolower() is always available. mb_strtolower() is only available if the additional mbstring module is loaded. The function overloading feature allows to use the "generic" call to strtolower() which will actually execute mb_strtolower() if configured such. So there actually is no need to explicitly code mb_strtolower() at all...

This makes code more portable, since it can run on systems with or without the mbstring extension.

like image 103
arkascha Avatar answered Oct 24 '22 13:10

arkascha


The strtolower() is a native function and will always be there compared to mb_strtolower() which is only available if the mbstring module is installed \ enabled.

But on the question why one should be used over the other, well that is quite simple. You can use them both and only use mb_strtolower() when its needed and or is available.


If you script something you should not use any special characters in scripts, filenames, db structures, etc as it should be language independent to improve portability and by doing so it will remove inconsistency's between operating systems. Scripts can behave differently in other environments, for example Linux is case-sensitive on fs/db operations where Windows is not.

A script should not have to deal with its own special characters as it is unnecessary and it will:

  • Cost performance, strtolower() is much faster than mb_strtolower()
  • Lose portability if mbstring is not available on the server.

An example is if you use other systems like the PSR-4 autoloader.

$var = new \ns\ÇavA();

Will attempt to load "Çava.php" instead of "çava.php" because it fails lowering the case due to the fact that its using the native strtolower() functions creating an inconstancy. Instead, just keep it ASCII.


mb_strtolower() should only be used for user input/output where strtolower() should be used for system orientated case formatting.

This being said; strtolower() will be sufficient for most of anyone's needs, even for user input/output but then the question arises where and how you apply that data. Keep in mind if its just for output to the user there is always the CSS text-transform method.

like image 44
Xorifelse Avatar answered Oct 24 '22 14:10

Xorifelse