Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode to array and print each element as list item

I have a set of numbers in a table field in database, the numbers are separated by comma ','. I am trying to do the following:

Step 1. : SELECT set of numbers from database and explode it to array :

$array =  explode(',', $set_of_numbers);

Step 2. : Print each element of the array as list item by using foreach loop :

foreach ($array as $list_item => $set_of_numbers){
    echo "<li>";
    print_r(array_list_items($set_of_numbers));
    echo "</li>";}

Please anybody tell me what is wrong. Thank you.

like image 751
user2170133 Avatar asked Apr 27 '13 21:04

user2170133


People also ask

What does the explode () function return?

The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

What does the explode () function do?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.

What is the purpose of the explode () and implode () functions in PHP?

The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.


2 Answers

$numbers = '1,2,3';

$array =  explode(',', $numbers);

foreach ($array as $item) {
    echo "<li>$item</li>";
}
like image 111
Danil Speransky Avatar answered Oct 13 '22 23:10

Danil Speransky


Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:

$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
   echo "<li>$key: $value</li>";
}

Assuming that 1,2,3,4... string, you'd get

<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...
like image 44
Marc B Avatar answered Oct 14 '22 00:10

Marc B