Undefined index error while key exists in array

Viewed 475

I'm pulling my hair on a proble which seems very simple, but I can't find a solution.

I have a simple $row array here :

array:2 [▼
  "reference" => "ABCDEF"
  "quantity" => "10"
]

I'm trying to parse it and retrieve quantities per reference using :

$line = [
  'ref' => strtoupper($row["reference"]),
  'quantity' => $row["quantity"]
];

I'm looping through array of lines using this code:

foreach ($rows as $row) {               
  $line = [
    'ref' => strtoupper($row['reference']),
    'quantity' => $row['quantity']
  ];
}

As a test, my main array $rows has 2 lines :

^ array:3 [▼
  0 => array:2 [▼
    0 => "ABCDEF"
    1 => "10"
  ]
  1 => array:2 [▼
    0 => "WXCVBN"
    1 => "3"
  ]
  2 => array:1 [▼
    0 => null
  ]
]

However, I'm getting the following error :

Undefined index: reference

Strangely enough, if I comment out the

'ref' => strtoupper($row["reference"]),

line, I can get the "quantity" value with no issue...

I know the key is in there, since the debug of the $row object gives the above result.

It must be dead simple... but I can't find the solution...

If anyone could please help ?

2 Answers

So apparently the $row variable a row from a bigger array that is used in a foreach loop. This might be the solution to your problem.

$array = [
  [ "reference" => "ABC", "quantity" => "10"],
  [ "reference" => "ABC", "quantity" => "10"],
  [ "reference" => "ABC", "quantity" => "10"],
];

$line[] = '';

foreach($array as $row)
{
    $line['ref'] = $row['reference'];
    $line['quantity'] = $row['quantity'];
}

In this example $array is your bigger array, i use it to test the example. After that i create a empty array $line to append the "new" data.

Could you try this?

Edit:

After taking a look at your loop and the array i noticed that your array doesnt have a reference key. Can you try strtoupper(row[0])?

Viewing your code seems that you convert $row array to $line without rewrite key in new array.

your code

    foreach ($rows as $row) {
        $line = [
            'ref' => strtoupper($row['reference']),
            'quantity' => $row['quantity']
        ];
    }

With your rewrite you can access $line data by index, not by key

array:3 [▼
  0 => array:2 [▼
    0 => "ABCDEF"
    1 => "10"
  ]
  ...
]

My solution

If you want to access your $line data by key, you need to rewrite your loop as:

foreach($rows as $rowData) {
    foreach($rowData as $rowKey => $rowValue) {
        $data = [
            'ref' => $rowKey => strtoupper$($rowValue),
            'quantity' => $row['quantity']
        ];
    }
    $line[] = $data;
}

Related