jidu
jidu

Reputation: 13

How to replace data in array

Current array structure

array:2 [
  "name" => "john"
  "data" => array:3 [
    0 => array:2 [
      "id" => 191109
      "ref_num" => "INV9002"
    ]
    1 => array:2 [
      "id" => 191110
      "ref_num" => ""
    ]
  ]

I'm trying to copy id to ref_num if ref_num is null. So far I did try like

Code

$izero = //that data structure above

foreach($izero['data'] as $key => $value) {
        if($value['ref_num'] === null) {
            $value['ref_num'] = $value['id'];
        }
        $izero['data'] = $value;
    }

$echo $izero

The result in izero missed the second array. It only keep the first array. Example if my data got 50 arrays, now it become the only one with first array.

The expected result should be like

array:2 [
  "name" => "john"
  "data" => array:3 [
    0 => array:2 [
      "id" => 191109
      "ref_num" => "INV9002"
    ]
    1 => array:2 [
      "id" => 191110
      "ref_num" => "191110"
    ]
]

Upvotes: 0

Views: 56

Answers (3)

Barmar
Barmar

Reputation: 780871

The other answers show how to fix this using a reference variable. If you want to assign to the array, you need to index it with $key:

foreach($izero['data'] as $key => $value) {
    if($value['ref_num'] === null) {
        $value['ref_num'] = $value['id'];
    }
    $izero['data'][$key] = $value;
}

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

There are a couple of tweaks to the code, if you change the foreach to use &$value, then you can update the value in place and not have to reassign the value at the end of the loop.

Also you have ($value['ref_num'] === null), as your checking for it to be null (in both value and type) and your array seems to have "". So you should change the test...

foreach($izero['data'] as $key => &$value) {
    if(empty($value['ref_num'])) {
        $value['ref_num'] = $value['id'];
    }
}

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

You overwrite $izero['data'] each time. Just reference & the value and then you can change it:

foreach($izero['data'] as &$value) {
        if($value['ref_num'] === null) {
            $value['ref_num'] = $value['id'];
        }
}

Or modify it by key:

foreach($izero['data'] as $key => $value) {
        if($value['ref_num'] === null) {
            $izero['data'][$key]['ref_num'] = $value['id'];
        }
}

Also, you don't show the actual value of the data and empty string "" is NOT === to null. You may want empty that checks for "", 0, null and false:

        if(empty($value['ref_num'])) {

Upvotes: 1

Related Questions