Search code examples
phpexplodeimplodepreg-split

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


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 :((


Solution

  • 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.