Search code examples
phparraysquery-stringexplodearray-key

Why isn't php explode extracting array values


I have some date values (each with a trailing = sign) stored as a &-delimited string.

My $_POST['dates'] string looks like this:

23.08.18=&22.08.18=&21.08.18=

I'm trying the following PHP code to extract the dates before inserting them into my database table. The code is currently not working.

foreach(explode('&', $_POST['dates']) as $value)  
{
    $value1 = explode('=', $value);
    foreach ($value1 as $x) {
    }
}

How can I isolate the date values?


Solution

  • <?php
    
    $data = '23.08.18=&22.08.18=&21.08.18=';
    
    //$delimiters has to be array
    //$string has to be array
    
    function multiexplode ($delimiters,$string) {
    
     $ary = explode($delimiters[0],$string);
     array_shift($delimiters);
     if($delimiters != NULL) {
        foreach($ary as $key => $val) {
            $ary[$key] = multiexplode($delimiters, $val);
        }
     }
     return  $ary;
    }
    
    $exploded = multiexplode(array("=","&"),$data);
    
    var_dump($exploded);
    

    The result should be:

    array (size=3)
      0 => string '23.08.18' (length=8)
      2 => string '22.08.18' (length=8)
      4 => string '21.08.18' (length=8)
    

    We need to use array_filter.

    http://php.net/manual/en/function.explode.php

    [EDIT] mickmackusa's answer is the right tool for parse url parameters into variables.