Search code examples
phpforeachcustom-lists

PHP - Converting codes to items


I have a list of approximately 300 standard codes, each of which relate to a specific item - e.g 001 is a t-shirt, 002 is a hat etc. What I need to be able to do is pass a code to a function and return the information that relates to the code, in PHP.

Effectively I'd like to do something like (apologies for the horrific pseudocode:

foreach($code){
----look up information
----return information
}``

What's the best way of going about this without relying on a huge case block?

Just to clarify, with some further information:

I have a standardised list that describes what all of the 300 ish codes equate too, e.g 001 is a t-shirt, 002 is a hat.

I'm retrieving data from a web service, as part of the response there is a list of codes that relate to the particular call that I'm making which I'm then turning into an array of codes to do with that product. These codes are provided standalone and as such I need to get the information relating to that particular code from the standard list.

So, if a web service call returns a set of codes I'm placing them into an array as such:

$codes = array(1,2,3)

Then what I need to be able to do is for each of the codes in the array is to find from the standard list what the equivalent data is.


Solution

  • You can do it this way using array:

    function getItem($code) {
    
       $array['001'] = 't-shirt';
       $array['002'] = 'hat';
    
       return isset($array[$code])  ? $array[$code] : false;
    }