So recently I was working on fixing an older system which is using keys from an array to retrieve certain data.
This is the array with several brands of cars, the key is used to filter certain things so the URL would look like http://example.com/page?brands=1&foo=bar
public static $carBrandGroups = [
0 => 'Volvo',
1 => 'BMW',
2 => 'Renault',
3 => 'Tesla',
4 => 'Opel',
5 => 'Peugeot',
6 => 'Toyota',
7 => 'Mercedes',
8 => 'Honda',
9 => 'Fiat',
]
Now the system works and retrieves everything except when 0 is passed which is logical since 0 is considered empty. I believe there must be a way, is there?
The function which passes additional information is shown below:
public static function getCarBrandGroup($modelNumber)
{
if ($modelNumber == 999) {
return 'Other';
}
if (isset(self::$carBrandGroups[$modelNumber[0]])) {
return self::$carBrandGroups[$modelNumber[0]];
}
return 'Unknown';
}
The modelNumber is three digits so everything that starts with 0 is a volvo model, so 001 is Volvo V40, 101 is BMW X6 and so on...
Like I stated above, everything works except for 0, is there a way to make this work and seen as a value?
Thank you in advance.
I'll asume the $modelNumber
is a string with 3 characters in it. In your example you're passing $modelNumber[0]
and it should result in an error.
Option 1: split your string into an array
public static function getCarBrandGroup($modelNumber)
{
if ($modelNumber == 999) {
return 'Other';
}
// Split your string into an array
$modelNumber = str_split($modelNumber);
if (isset(self::$carBrandGroups[$modelNumber[0]])) {
return self::$carBrandGroups[$modelNumber[0]];
}
return 'Unknown';
}
Option 2: use the first character to get the required model
public static function getCarBrandGroup($modelNumber)
{
if ($modelNumber == 999) {
return 'Other';
}
// Get the first character using substr
$modelNumber = substr($modelNumber, 0, 1);
if (isset(self::$carBrandGroups[$modelNumber])) {
return self::$carBrandGroups[$modelNumber];
}
return 'Unknown';
}
Option 3: Or if you like shorthand & fancy PHP7 operators:
public static function getCarBrandGroup($modelNumber)
{
if ($modelNumber == 999) {
return 'Other';
}
return self::$carBrandGroups[substr($modelNumber, 0, 1)] ?? 'Unknown';
}
You're most likely getting passed integer 1
instead of string 001
. If you know that each code is supposed to have exactly three digits, then you can force a zero-padded reformat and cast to string at the same time by using sprintf()
:
public static function getCarBrandGroup($modelNumber)
{
$modelNumber = sprintf('%03d', $modelNumber);
if ($modelNumber === '999') {
return 'Other';
}
if (isset(self::$carBrandGroups[$modelNumber[0]])) {
return self::$carBrandGroups[$modelNumber[0]];
}
return 'Unknown';
}
Now, you can pass either (string) "001"
or (int) 1
.