Help with a "Warning: Undefined array key" issue

Hello,
I am getting this warning Warning: Undefined array key when using the below code. This does return the correct value but I would like to fix the warning. The error says it is on the return line.

$locationId = '47V9D0K01JHXW';
private function getLocationMap($locationId) {
$warehouseMapArray = [];
		
		$warehouseMapArray['LSAJRJW8STWCQ'] =  1;
		$warehouseMapArray['LCF7PX9Q1ZAZ4'] =  3;
		$warehouseMapArray['L4Y9KP6KS7T30'] =  5;
		$warehouseMapArray['L9JKX4EKKK73J'] =  7;
		$warehouseMapArray['LNKAWM61JN12A'] =  8;
		$warehouseMapArray['LRWTPNRB246QV'] =  9;
		$warehouseMapArray['LTRB1Q315ESHW'] =  10;
		$warehouseMapArray['LX96YYQ39QCQS'] =  11;
		$warehouseMapArray['LQ4TKZ5WPK1WB'] =  17;
		$warehouseMapArray['47V9D0K01JHXW'] =  16;



		return $warehouseMapArray[$locationId];

}```

Any ideas is really appreciated.

Thanks
Don

You’d need to show us where getLocationMap() is called, and what it’s passing as the $locationId parameter. But clearly the parameter it’s passing is not one of the strings you’ve encoded in the array.

The location id I put just above the method is what is being passed. I actually get back a value of 16 which is correct. But I am still getting the warning.

Which line, specifically, is throwing the warning?

The return line.

And you’re absolutely sure that you’re only calling getLocationMap once, and only with the correct id in place?

tracknut’s correct, something is calling getLocationMap with a bad ID somewhere.

What is in $locationId when you display it inside the function for debugging purposes?

I make a habit of not using variable names that are the same as parameter names, where I can, to remove any kind of confusion. Seeing that you use it as the variable name in your calling code, and the parameter name inside your function, just adds a little potential for confusion to the casual viewer, even if the compiler isn’t confused.

Maybe you want to add a little check as you never know if the correct value will be passed.

		if(!empty($locationId) && array_key_exists($locationId,$warehouseMapArray)){
			return $warehouseMapArray[$locationId];	
		}else{ 
			return "n/a";
		}

Also is this function within a CLASS and called where $locationId = '47V9D0K01JHXW'; is not available such as outside the CLASS?

Null Coalesce.

Yes, writing as a single line would be better.

return ((!empty($locationId) && array_key_exists($locationId,$warehouseMapArray)) ? $warehouseMapArray[$locationId] : "n/a");

What you have shown is not calling the function so there shouldn’t be an error in the function. I guess we would all like to see how you are calling the function… Something like this with a value key inside the call?

echo getLocationMap('47V9D0K01JHXW');

How are you testing this function if you are not calling it?