Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array values in a sequence [closed]

Tags:

arrays

string

php

Hi i am retrieving values from my database to my web page. here is my code

foreach ($rows as $r) { 
    echo $r->title;
}

Now I want all my title values to be saved in a single variable separated by commas for example

$new_var = title_1,title_2,title_3;

how can i do that??

like image 748
Abbasi Avatar asked Jul 10 '26 21:07

Abbasi


2 Answers

$items = array();
foreach ($rows as $r)
        { 

$items[] = $r->title;

}

$new_var = implode(",", $items);

Using implode. This is quick and easy and handles the issue of a trailing comma that has to be fixed with other methods.

like image 101
Mattt Avatar answered Jul 13 '26 14:07

Mattt


Use implode:

$new_var = array();
foreach ($rows as $r) { 
    echo $r->title;
    $new_var[] = $r->title;
}
$new_var = implode(',',$new_var);
like image 20
Sergey Avatar answered Jul 13 '26 12:07

Sergey



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!