With the method you were initially trying, it is also possible to get the expected result.
However, using the for
on account of the fact that array, in the example, you will have 6 items, the for
will try to run the same process 6 times. Then, doing so:
for ($i = 0; $i < count($arraydados); $i++) {
$arrayinsert[$arraydados[$cntindice]] = $arraydados[$cntvalor];
$cntindice += 2;
$cntvalor += 2;
}
It will occur of $cntindice
and $cntvalor
get the values: 0 (valor inicial), 2, 4, 6, 8, 10
and 1 (valor inicial), 3, 5, 7, 9, 11
, respectively. But, as the array only has 6 items, the last valid positions will be 4 for $cntindice
and 5 to $cntvalor
, and henceforth shall return null (or emptiness).
And therefore, from position 6, both the key and the value will be null (or emptiness), and from there it will be replaced until the loop iteration ends.
So that it doesn’t happen instead of for
, you can use a while
, thus:
$dados = "name-luiz-idade-21-status-true";
$arraydados = explode("-", $dados);
$arrayinsert = array();
$posicaoChave = 0;
$posicaoValor = 1;
while ($posicaoChave < count($arraydados) && $posicaoValor < count($arraydados)) {
$chave = $arraydados[$posicaoChave];
$valor = $arraydados[$posicaoValor];
$arrayinsert[$chave] = $valor;
$posicaoChave += 2;
$posicaoValor += 2;
}
//print_r($arrayinsert);
That is, as long as $posicaoChave
and $posicaoValor
are smaller than the size of the array, executes the code block. Thus, when $posicaoChave
become 6 and $posicaoValor
if it becomes 7, the condition of the loop will not be satisfied, so it will not execute the block, and consequently will not generate an unnecessary/invalid position in the array.
I hope I’ve helped!
Why not create an object ?
– ScrapBench