w3resource

PHP Array Exercises : Display array values in a list


2. Display Colors in Specific Format

$color = array('white', 'green', 'red'')
Write a PHP script which will display the colors in the following way :

Sample Solution:

PHP Code:

<?php
// Define an array of colors
$color = array('white', 'green', 'red');

// Iterate through each color in the array and echo them with a comma separator
foreach ($color as $c) {
    echo "$c, ";
}

// Sort the colors alphabetically
sort($color);

// Echo the start of an unordered list
echo "<ul>";

// Iterate through each color in the sorted array and echo them as list items
foreach ($color as $y) {
    echo "<li>$y</li>";
}

// Echo the end of the unordered list
echo "</ul>";

?>

Output:

white, green, red,

  • green
  • red
  • white

View the output in browser

Flowchart:

Flowchart: Display array values in a list

For more Practice: Solve these Related Problems:

  • Write a PHP script that prints the elements of a color array as a comma-separated string and then on separate lines in reverse order.
  • Write a PHP function to output the color names from an array in both a horizontal comma-separated format and a vertical list, ensuring trailing commas are handled correctly.
  • Write a PHP program that takes an array of colors and outputs them in a formatted table that shows them in the original order and then in reverse order.
  • Write a PHP script that formats the color array into two distinct sections: one with colors separated by commas and another with colors sorted alphabetically and printed line-by-line.

Go to:


PREV : Colorful Memory String.
NEXT : Sorted Capitals from CEU Array.



-->

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.