简体   繁体   中英

Print array with alternate colour in PHP

I have an array,

$arr = arrary("Pune","Nashik","Mumbai");

I want to display Pune in red colour, then on the next line Nashik will be blue and the last line will have Mumbai in green. How do I do this using a " while loop ".

Like,

Pune (in red) 
Nashik (in blue) 
Mumbai (in green)

Why don't you simply build the logic into the array, eg

$arr = array(
    'Pune'   => '#ff0000',
    'Nashik' => '#0000ff',
    'Mumbai' => '#00ff00'
);

Then, when you loop over it, use CSS to display the colours.

<?php foreach ($arr as $something => $colour) : ?>
    <p style="color:<?php echo $colour ?>"><?php echo $something ?></p>
<?php endforeach ?>

You could also use CSS class names instead of hex colour values.

Also, a while loop is hardly the best option for iterating over an array.

Edit: Oops, accidentally deleted my second example. It's back now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM