Search code examples
phpexplodefqdn

PHP: array_pop returns the empty string


I'm using explode to break a FQDN and store it in an array. Calling pop on that array however returns a blank or empty string, and I can't figure out why.

 $domains = explode(".",str_replace("example.com","","test.example.com"));
 print "Test: " . $domains[0] . "<br>";
 $target = array_pop($domains);
 print "Target: " . $target . "<br>";

Running the above code results in:

 Test: test
 Target: 

Why doesn't $target contain "test"?


Solution

  • In effect, here's what you're actually doing:

    var_dump(explode('.', 'test.'));
    
    array(2) {
      [0]=>
      string(4) "test"
      [1]=>
      string(0) ""
    }
    

    You get two elements in the array: "test" and what's after the period i.e. an empty string.