I have the following switch function on a website, however the data ($data) I now need to feed into it is a comma separated list i.e. AG,GCG,POA,CON,SPE
If AG is the first on the list it works, but the CSV string might not always be in the same order. There will always only be one of the below codes in the string, I want to extract this code and turn it into it’s real name if it exists, how would I go about this? I believe I need an array, so the items of my array will be each item separated by a ","
<?php
function division($data)
{
switch ($data){
case 'AG':
return 'Agricultural Machinery';
case 'GCG':
return 'Groundcare & Garden Machinery';
case 'CON':
return 'Construction Machinery';
default:
return false;
}
}
?>
2
Answers
You can split the comma-separated string into an array using the PHP
explode
function. Then you can loop through the array and check each item against your switch statement until you find a match. Once you have found a match, you can return the corresponding value.In this code, the
$data
parameter is first split into an array usingexplode(',', $data)
, which will split the string at every comma and return an array of the resulting values. Then, theforeach
loop will iterate over each item in the array and check it against theswitch
statement. If a match is found, the corresponding value is returned. If no match is found, the function will return false.If I got this right, I would do something like this: