Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Laravel collection increment values and keys

Hello,

How do I decrement all keys from a collection and convert it to an array?

So let's say I've a collection that looks like this:

Collection {#410 ▼
  #items: array:1 [▼
    1  => 1,
    2 => 6  
  ]
}

I need that to convert like this:

array:1 [▼
  0 => 1,
  1 => 6
]

I know I can do:

$collection->toArray();

But than I get this:

array:1 [▼
  1 => 1
]

I already looked at the docs but can't find it!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can just make a new array from the collection by looping over the existing collection and assigning the key to be the same as the current key -1.

$newCollection = collect([]);
$collection->each(function($item, $key) use ($newCollection) {
    $newCollection->put($key-1, $item);
});


//$newCollection has decremented keys
over 4 years ago · Santiago Trujillo Report

0

From the described desired output it looks like you can use native PHP function array_values which

returns all the values from the array and indexes the array numerically.

http://php.net/manual/en/function.array-values.php

array_values($collection->toArray())
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!