0

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"
    ]
]

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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'])) {

Comments

1

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'];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.