Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seperate comma separated mySql database field value with php

If you believe this is a duplicate please let me now as I'm not totally sure what to search for to check, (I will remove if duplicate)

I have a list of of numbers in a mySql field called sess_times in a table called test_sess, the numbers for the first row are:

25, 38, 40, 50

is it possible to split these into php variable e.g:

$no1 = 25
$no2 = 38
$no3 = 40
$no4 = 50

I'm trying to put the individual numbers in a table, something like below:

<table cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td> 1 </td>
    <td><?php echo $no1; ?></td>
  </tr>
  <tr>
    <td> 2 </td>
    <td><?php echo $no2; ?></td>
  </tr>
  <tr>
    <td> 3 </td>
    <td><?php echo $no3; ?></td>
  </tr>
  <tr>
    <td> 4 </td>
    <td><?php echo $no4; ?></td>
  </tr>
</table>

Any help with this would be great so thanks in advance for any answers.

HERE'S THE SOLUTION I USED, A COMBINATION OF 2 ANSWERS BELOW:

$data = '25,38,40,50';
$string = explode(",", $data);
$number = 0;
echo '<table cellspacing="0" cellpadding="0" border="0">';
for($i=0; $i<count($string); $i++)
{
    $number = $number +1;
    echo '
        <tr>
            <td>' . $number . '</td>
            <td>' . $string[$i] . '</td>
        </tr>
    ';
}
like image 921
huddds Avatar asked Dec 04 '25 07:12

huddds


2 Answers

You can use PHP's explode function.

When you output everything, save it into a variable.

Then, $string = explode(",", $string); will produce this:

Array ( [0] => 28[1] => 38 [2] => 40 [3] => 50 )

To output this, you can then use $string[number] for each value.

like image 115
Albzi Avatar answered Dec 06 '25 22:12

Albzi


You can explode them

$string="25,38,40,50";
$numbers=explode(",",$string);
print_r($numbers); // You can use them for printing like echo $numbers[0]; or 1 or 2 or 3

And if you don't want the result in an array and still want those 4 variable names you can do this

$string="25,38,40,50";
list($no1,$no2,$no3,$no4)=explode(",",$string);
like image 27
Hanky Panky Avatar answered Dec 07 '25 00:12

Hanky Panky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!