How to use array_map() and implode() Function In PHP

Using array_map() and implode() function provides a functional approach to generate the HTML list.

  • The createList function takes an array as an argument.
  • It uses array_map() to apply a callback function to each element of the array, wrapping each item in <li> tags.
  • The resulting array of list items is then joined into a single string using implode.
  • The function wraps the list items in <ul> tags and returns the resulting HTML string.

Example: This example shows the creation of HTML list from an array using array_map() and implode() Function.

PHP
<?php

function createList($arr) {
    $listItems = array_map(function($item) {
        return '<li>' . htmlspecialchars($item) . '</li>';
    }, $arr);
    return '<ol>' . implode('', $listItems) . '</ol>';
}

// Driver code
$arr = ['HTML', 'CSS', 'JavaScript', 'PHP'];
echo createList($arr);

?>

Output
<ol><li>HTML</li><li>CSS</li><li>JavaScript</li><li>PHP</li></ol>

How to Create HTML List from Array in PHP?

Given an array containing some items, the task is to create an HTML list from an array in PHP. An HTML list is a collection of items enclosed within <ul> (unordered list) or <ol> (ordered list) tags. Each item in the list is enclosed within <li> (list item) tags. This article explores different approaches to converting an array into an HTML list.

Table of Content

  • Using foreach Loop
  • Using array_map() and implode() Function
  • Using array_reduce() Function

Similar Reads

Using foreach Loop

The foreach loop is a basic method to iterate over an array and generate the corresponding HTML list items....

Using array_map() and implode() Function

Using array_map() and implode() function provides a functional approach to generate the HTML list....

Using array_reduce() Function

The array_reduce() can be used to build the HTML list by accumulating the result in a single string....