skip to Main Content

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


  1. 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.

    function division($data)
    {
        $items = explode(',', $data);
        foreach ($items as $item) {
            switch ($item){
                case 'AG':
                    return 'Agricultural Machinery';
                case 'GCG':
                    return 'Groundcare & Garden Machinery';
                case 'CON':
                    return 'Construction Machinery';
            }
        }
        return false;
    }
    

    In this code, the $data parameter is first split into an array using explode(',', $data), which will split the string at every comma and return an array of the resulting values. Then, the foreach loop will iterate over each item in the array and check it against the switch statement. If a match is found, the corresponding value is returned. If no match is found, the function will return false.

    Login or Signup to reply.
  2. If I got this right, I would do something like this:

    
    function division($data)
    {
        $initials = [
            'AG' => 'Agricultural Machinery',
            'GCG' => 'Groundcare & Garden Machinery',
            'CON' => 'Construction Machinery'
        ];
        
        if(array_key_exists($data, $initials)) return $initials['data'];
        return false;
    
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search