Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dev0ps's avatar

array_slice() expects parameter 1 to be array, object given

$a = Post::take(5)->get();

my code

function down($a,$x) {
            if( count($a)-1 > $x ) {
                $b = array_slice($a,0,$x,true);
                $b[] = $a[$x+1];
                $b[] = $a[$x];
                $b += array_slice($a,$x+2,count($a),true);
                return($b);
            } else { return $a; }
        }
        function up($a,$x) {
            if( $x > 0 and $x < count($a) ) {
                $b = array_slice($a,0,($x-1),true);
                $b[] = $a[$x];
                $b[] = $a[$x-1];
                $b += array_slice($a,($x+1),count($a),true);
                return($b);
            } else { return $a; }
        }
// Start
      return up($a,1);

this code is working with

$a = array('a','b','c','d','e');
0 likes
1 reply
lostdreamer_nl's avatar
Level 53
$a = Post::take(5)->get()->toArray();

get() will give you a collection object, not an array You'll have to turn it into an array first.

1 like

Please or to participate in this conversation.