PHP

Frequent PHP problems and solutions

I started off with frequent CakePHP problems last month. This month I add some common PHP problems.

Strip additional white spaces

With UTF8 the "normal" preg_replace doesn’t really work anymore. For some cases we could use the following trick:

$str = utf8_decode($str);
$str = preg_replace('/\s\s+/', ' ', $str);
$str = utf8_encode($str);

A better solution, though, is:

$str = preg_replace('/\s\s+/u', ' ', $str);

With the param "u" it’s compatible with Unicode.

Sort arrays in natural order

$array = array('1.txt', '20.txt', '2.txt', '21.txt');
natsort($array); # sorts by reference (returns boolean $success)

Condition + assignment

If you want to save the extra line for $pos = $this->calcPos()) you need to be aware that extra brackets might be needed.
Wrong (if $pos is supposed to hold the position and not the result of the comparison):

if ($pos = $this->calcPos() > 0 && ...) {...}

Correct:

if (($pos = $this->calcPos()) > 0 && $pos < 100) {
    # doSomething
    $pos++;
    # doSomethingElseWithPos
}

Note the extra brackets around $pos. They are necessary – otherwise it will assign the result of the operation $this->calcPos()) > 0 (which is a boolean).

Comparison (default and strict)

Since PHP isn’t type safe you should use strict comparison (===) wherever possible.
"+010" == "10.0" is TRUE (!)
only with "+010" === "10.0" you will get FALSE.
This might be expected in this case – usually it’s not, though.
So it is not if (strpos($str, 'hello') == 0) {} but if (strpos($str, 'hello') === 0) {}, for example! What happens in the == case?
It will return true in 2 cases: If "hello" is not in the string at all or if it is at the very beginning. But we would only want the second case (and therefore need ===).

A complete comparison table for PHP can be found here.

4.00 avg. rating (83% score) - 1 vote

5 Comments

  1. For the additional spaces you can use

    mb_ereg_replace('/\s\s+/', ' ', $str)

    if you have mbstring support.

  2. Today I found out THAT even with php5.3.3 mb_ereg_replace() is quite buggy!

    So we should use

    preg_replace with parameter "u":

    $string = preg_replace("/\s\s+/u", " ", $string);

    This way we don’t need to decode/encode.

  3. plz any one can solve my problem???
    problem is when ever i click on link on my website’s nav link…the links does not work properly….
    and page goes again on login page….

    any one have solution???

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.