Neat PHP trick for alternate background display

Neat PHP trick for alternate background display

Many is the time we have to use alternate background for displaying some data. The usual solution to this problem would look something like:

Which in my opinion is somewhat a dirty solution. So I did a little research and found a bit neater solution:

It might even be a bit faster but I have not done any benchmarking.

2 Responses so far.

  1. As an alternative, you could use the array_map() function and convert the array of data into a structure that already has the even parameter defined:

    In the controller:

    $convertedData = [];
    $convertedData = array_map(function($d, $n) {
    array_push($convertedData, array(“even” => $n % 2, “data” => $d));
    }, $rawData, range(0, count($rawData) – 1));

    In the template, passing the transformed view model to the template:

    foreach($convertedData as $data) {
    if($data[“even”])
    $data[“data”]…
    else

    }

    Preparing the view model before passing it to the template is IMHO a cleaner solution, since any code that does variable assignment in the template is unclean. Although this approach requires a bit more RAM and CPU, it is the cleaner way of doing MVC.

  2. smottt says:

    That’s an even neater solution. I actually never thought of doing it that way. Thanks for suggesting it.