0

I have an array ($cart) that I want to process in a foreach loop either in reverse order or in normal order depending on an external switch. The code below gives the idea of what I am trying to do,

switch ($data['entire_receipt'])
    {
        case    'N':
            $foreach    =   'array_reverse($cart, true) as $line=>$item';
            break;
        case    'Y':
            $foreach    =   '$cart as $line=>$item';
            break;
        default:
            $foreach    =   'array_reverse($cart, true) as $line=>$item';
    }

    //foreach   $$foreach
    foreach ("$foreach")
    {
       // do something
    }

The code within the foreach loop is exactly the same whether processed in reverse or normal order.

The above fails on the "foreach ("foreach")" line.

Obviously I could use if statements but then I would have to duplicate the do something code, which adds maintenance complexity.

Is there a solution to this?

Thanks for your help.

Hilary
  • 13
  • 7
  • You must use [eval()](http://php.net/manual/en/function.eval.php) to execute code stored in a string. – davidkonrad Feb 21 '15 at 13:23
  • Thanks for your answer. I am aware that eval is dangerous but since I am providing the code from within my script it would seem OK to use. – Hilary Feb 21 '15 at 13:29
  • eval() can still cause problems with error reporting, it isn't just a potential security issue..... and it's totally unnecessary to use in this situation – Mark Baker Feb 21 '15 at 13:32
  • eval() is not always evil -> http://stackoverflow.com/a/951868/1407478 I can and will not judge if eval() is inappropriate here, all I say is that it is the way to go if you want to execute code stored in a string. – davidkonrad Feb 21 '15 at 13:38

2 Answers2

1

You can't simply create strings and expect them to be executed as code

switch ($data['entire_receipt']) {
    case 'Y' :
        $foreach = $cart;
        break;
    case 'N' :
    default  :
        $foreach = array_reverse($cart, true);
}

foreach ($foreach as $line => $item) {
   // do something
}

Note that $foreach is a copy of the $cart array, if you want to directly modify the $cart array in your foreach loop, then use the $line value as the key to $cart

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Yo should iterate the same variable and reverse the array if it's necessary.

if ($data['entire_receipt']) == 'N') {
    $cart = array_reverse($cart, true)
}

foreach ($cart as $line => $item) {
  // Do something
}
Jordi Llull
  • 810
  • 6
  • 17