How to Split/Explode a string into a numbered lists in PHP?

Viewed 162

I am trying to split this string into numbered lists..

str options is "Hello,Howdy,Hola".

I need the output to be

  1. Hello
  2. Howdy
  3. Hola

This is my code

$newstr = 'My values are' . explode(",", $str["options"]) . '<br/>';

However, This causes to only print the word Array. Please help me on this :((

3 Answers

a) explode() with comma to make string as an array.

b) Iterate over it and concatenate number and text.

c) Save all these concatenated values to one string.

d) echo this string at end.

<?php
$str["options"] = "Hello,Howdy,Hola";
$data = explode(",", $str["options"]);

$newstr = 'My values are'. PHP_EOL;
foreach($data as $key => $value){
    $number = $key+1;
    $newstr .= "$number.". $value . PHP_EOL;
}
echo $newstr;

https://3v4l.org/lCYMk

Note:- you can use <br> instead of PHP_EOL as well.

Try this, it will print this out in an html list tag

   <ol>

   <?php 

   $option = '';

   $newstr =  explode(",", $str["options"]) ;

   foreach($newstr as $option) {

   $option = trim($option); ?>

   <li><?php echo $option; ?></li>

  <?php } ?>

  </ol>

First, you need to explode your array. That will create an indexed array, which starts the index from 0 up to 2. Next, you will need to implode it in some manner. Other answers are more explicit and use foreach, so this one provides an alternative, where you convert your array into the desired format via array_map. The function passed to array_map is a so-called callback, a function that is executed by array_map for each element, in this case, which is aware of the key and the value of each element. Now, we implode our input and, to make sure that we have some keys, we pass the result of array_keys.

$input = explode(",", "Hello,Howdy,Hola");
$output = implode('<br>', array_map(
    function ($v, $k) {
        return ($k + 1).'. '.$v;
    }, 
    $input, 
    array_keys($input)
));
Related