Search code examples
phpphp-7

Why does explode return whole array?


This code returns whole array instead false or NULL, because there are not matches by mask ;

$a = " 6 . 2 . 828194 . 2 . 3 .";

var_dump(explode(';', $a));

How to solve this feature?

Result is:

array(1) { [0]=> string(25) " 6 . 2 . 828194 . 2 . 3 ." }

Solution

  • You can just test if the delimiter is there before exploding and do what you want if it's not there.

    $a = " 6 . 2 . 828194 . 2 . 3 .";
    $delim = ";";
    
    if(strpos($a, $delim) !== false){
        var_dump(explode($delim, $a));
    }else{
        echo "null";
        // Or
        // $a[] = Null;
    }
    

    Result: null