简体   繁体   中英

Strict Standards error, trying to reverse a string as array

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


Edit:

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?

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
<?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

Quick and easy:

$accounts = '1,2,3,4,5,6';

echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM