naeplus
naeplus

Reputation: 121

return array from function by passing string

i have following function where i have brands info in an array. i should get array containing those info when i pass brand name to this function.

function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );


    if(in_array($brand,$brands_list))
    {
        // return array containg company info
    }
}

this should return an array by which i can show these info.

$brand_info=brand_info($brand_name);
echo $brand_info['name'];

what may be the best way to do this?

Upvotes: 0

Views: 80

Answers (4)

Nick
Nick

Reputation: 6346

If you're passing in the brandname then this would suffice:

function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'Nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );

    if (array_key_exists($brand,$brands_list)) {
      return $brands_list[$brand];
    } else {
      return false;
    }
}

$brandinfo = brand_info('Nokia');
echo $brandinfo['name']; // will print "Nokia Phone Company"

Upvotes: 3

edelgado
edelgado

Reputation: 361

function brand_info($brand) {
    $brands_list=array (
        'lg'=>
            array(
                    'name'           => 'LG Phone Company',
                    'country'        =>  'country',
                    'founded_year'   =>  '2001'
            ),
        'Nokia'=>
            array(
                    'name'           => 'Nokia Phone Company',
                    'country'        =>  'country',
                    'founded_year'   =>  '2001'
            )
    );


    foreach ($brands_list as $brandname=>$info) {
        if($brandname==$brand) {
            return $info;
        }
    }
    return array();
}

Upvotes: 1

chrvadala
chrvadala

Reputation: 592

function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );


    if(in_array($brand,$brands_list))
    {
        return $brand_list[$brand];
    }else{
        return null;
    }
}

and then

$info = brand_info($my_brand);
if(!is_null($info)){ echo $info['name']; }

Upvotes: 1

Amarnasan
Amarnasan

Reputation: 15529

May seem trivial but...

return $brands_list[$brand]

Upvotes: 1

Related Questions