Yatko
Yatko

Reputation: 8805

Separate array values into two outputs (ex. odd / even) with one foreach loop (PHP) - split array output into two

I have this script that reads a list of domains from an external .ini file and transforms them into a list of links:

<?php
$listSeparator = ",";
$lines = file('list.ini');
foreach ($lines as $line) {
    $listvalues = explode('=',$line);

    echo implode("<br />",array_map("add_link",explode($listSeparator,str_replace(' ', '', $listvalues[1]))));
}

function add_link($n)
{
    return "<p><a href=\"$n\">$n</a></p>";
}
?>

what I am trying to achieve is having two outputs (odd/even), starting with the first value, something like this:

return "<section>
            <p class=\"odd\">
                <a href=\"{odd}\">{odd}</a>
            </p>
            <p class=\"even\">
                <a href=\"{even}\">{even}</a>
            </p>
        </section>";

Thanks in advance!

Upvotes: 0

Views: 234

Answers (1)

Ramy Nasr
Ramy Nasr

Reputation: 2537

easiest way to do that:

$odd = false;

function add_link($n)
{
    global $odd;

    $odd = !$odd;
    $class = ($odd) ? 'odd' : 'even';
    return "<p class=\"$class\"><a href=\"$n\">$n</a></p>";
}

Of course there are other concerns in the code about mixing HTML with PHP, functions and scopes, etc. but I just built upon your code.

also if you are using these classes only for styling you can use pure CSS: :nth-child()

( provided that you are not using older browsers )

Upvotes: 1

Related Questions