Reputation: 771
So I have a string with comma separated values:
$accounts = "1,2,3,4,5,6";
And I want to reverse that order. So I wrote this:
$accountsrev = implode(',',rsort(explode(',',$accounts)));
Basically I convert to an array, reverse the array, and implode it back into a string. What's wrong with that?
I get a load of errors like this:
Strict Standards: Only variables should be passed by reference in /home/username/public_html/file.php on line 121
Warning: implode(): Invalid arguments passed in /home/username/public_html/file.php on line 121
Now I wonder if the way I build the $accounts variable is wrong. I pull 7 rows from the database and then build the $accounts variable in a while loop. The id
is an integer in the database:
$accounts = '';
$i = 1;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
if ($i < 7) {
$accounts .= $data['id'].',';
} else {
$accounts .= $data['id'];
}
$i++;
}
Does the way I make the $accounts variable not produce a string?
Upvotes: 0
Views: 45
Reputation: 5690
<?php
$accounts = '';
$i = 0;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$i++;
if($i == 1){
$accounts = $data['id'];
} else {
$accounts .= $data['id'].',';
}
}
$accountsrev = explode(',',$accounts); // explode it as make array
rsort($accountsrev); // then use rsort which sort array reverse
$accountsrev = implode(',',$accountsrev); // again implode it
echo $accountsrev;
?>
then output will be
6,5,4,3,2,1
or you can use array_reverse ()
function instead rsort
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));
then output will be
6,5,4,3,2,1
Upvotes: 1
Reputation: 40673
This is just something that tells you you're doing something completely wrong:
$array = [1,2,3,4];
rsort($array);
//$array is sorted.
However:
rsort(array_filter($array));
//Array filter returned a copy of the original array so $array is neither sorted nor filtered.
You need to do:
$accounts = '';
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$accounts .= $data['id'].',';
}
$accountsrev = explode(',',rtrim($accounts,","));
rsort($accountsrev);
$accountsrev = implode(',',$accountsrev);//accountsrev is sorted here
Upvotes: 2
Reputation: 3178
Quick and easy:
$accounts = '1,2,3,4,5,6';
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));
Upvotes: 0