Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda