Search code examples
phpregexarrayspreg-match

PHP separate even and odd values from an array


I'm using the below code to separate odd and even and store it in different variable. When there are only 2 value available then it works fine but when the number value increases then it doesn't. I want to make it dynamic so that n number of values can be separated and stored correctly.

Example: If the value of

$final_array = "PNL testing 1,10,PNL testing 2,35,";

It prints nicely:

$teams = "PNL testing 1, PNL testing 2";

$amount = "10, 35";

But when it increases from

$final_array = "PNL testing 1,10,PNL testing 2,35,";

to

$final_array = "PNL testing 1,10,PNL testing 2,35,Team 3,95,";

Then also it prints

$teams = "PNL testing 1, PNL testing 2";

$amount = "10, 35"; 

Please guide me through on where I am going wrong.

$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $final_array, $res);
$teams = join(', ', $res[1]); //will display teams
$amount = join(', ', $res[2]); //will display amount every team have
echo $teams . "<br />" . $amount;

Solution

  • It will much easier I think to use explode:

    $result = explode(',', $final_array);
    
    $teams = array();
    $amount = array();
    
    foreach ($result as $key => $value) {
        if ($key % 2 == 0) {
            $teams[] = $value;
        } else {
            $amount[] = $value;
        }
    }
    
    $teams  = implode(', ', $teams); //will display teams
    $amount = implode(', ', $amount); //will display amount every team have
    echo $teams."<br />".$amount;