phparraysloopsexplode

Explode semicolon delimited string and iterate every two values


I have an array with a single value collected from database.

Within a while loop I wish to explode this for every two values.

Example:

$data = array('20;40;60;80;100;150;200;300;500;1000');

I want to explode this value and end up with the following loop:

$lowprice = "20";
$highprice = "40";

Solution

  • You can use preg_match_all().

    Example:

    $text = '20;40;60;80;100;150;200;300;500;1000';
    
    preg_match_all("/([^;]+);([^;]+)/", $text, $pairs, PREG_SET_ORDER);
    
    foreach ($pairs as $pair) {
        // ...
        $lowvalue = $pair[1];
        $highvalue = $pair[2];
        // ...
    }
    

    If you really must use explode and a while loop, the following will also work:

    $text = '20;40;60;80;100;150;200;300;500;1000';
    
    $data = explode(';', $text);
    
    $i = 0;
    $count = count($data);
    
    while ($i < $count) {
    // ...
        $lowvalue = $data[$i++];
        $highvalue = $data[$i++];
    // ...
    }