2

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

  • 1
    You can not output an array with echo, or use it in a string concatenation context. Either write a _loop_ to go through the individual array elements, and append them to your string one by one, or use `implode` to transform your array into a string again, with whatever needs to be appended _between_ the individual elements. – CBroe Jan 20 '21 at 10:34

3 Answers3

1

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.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

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>
Browyn Louis
  • 218
  • 3
  • 14
0

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)
));
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    Thank you for the answer. You explained really well and made it easier for me to understand. However, I have a syntax error at $output implode which prompts unexpected identifier "implode"...I am unable to pass this code.. Any ideas? – user6345655 Jan 20 '21 at 17:14
  • @user6345655 thanks for pointing that out. It was a typo in my code indeed, apparently I did not push the ```=``` character between $output and implode hard-enough. Edited my answer. – Lajos Arpad Jan 21 '21 at 07:57