Replace array value to increment

Cristal

New Member
#1
I have an array like this ...
Mã:
[0,0,23,0,0,18,0,0]
Then I want to change values that are not '0' (23 & 18) to auto increment, so the end result will be like this,
Mã:
[0,0,1,0,0,2,0,0]
is there the best way for all that? So far this is what I did, but the results were not as expected ... :)
Mã:
<?php

$arr = [0,0,23,0,0,18,0,0];
$x = 1;
$r = collect($arr)->map(function ($value, $key)use($x) {
    if ($value == 0) {
        return $value;
    } else {
        return $x++;
    }
})->all();

dd($r);
 

Admin

Administrator
Thành viên BQT
#2
The problem is that when you have your value of $x passed into the function via use, this isn't allowing the value to be updated. You need to pass it by reference - use (&$x) to allow it to increment the value outside the function...
Mã:
$r = collect($arr)->map(function ($value, $key) use (&$x) {
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top