Pigi
Pigi

Reputation: 74

Get value from php array that have the same key name

a quick answer about how to get the value (and pass it in a php variable) from an array:

i've this array:

$array = array(
            array('name' => 'infotel', 'value' => '+39080123456' ), 
            array('name' => 'location', 'value' => 'Bari')
            );

I need to pass the "value" of "infotel" in a $telephone variable, and the "value" of "location" in a $city variable.

how can i solve this trouble? thanks

Upvotes: 0

Views: 578

Answers (6)

ashish.negi
ashish.negi

Reputation: 534

You can get your desire result by using this code. you need not to worry about array keys. but last key will replace your location and telephone value.

$array = array(
            array('name' => 'infotel', 'value' => '+39080123456' ), 
            array('name' => 'location', 'value' => 'Bari')
            );
$key1 = '';
$key2 = '';
foreach($array as $k => $a){
    if(array_search('infotel', $a) != false){
        $key1 = $k;
    }
    if(array_search('location', $a) != false){
        $key2 = $k;
    }
}
echo 'telephone = '.$array[$key1]['value'];
echo 'location = '.$array[$key2]['value'];

Upvotes: 0

Mark Miller
Mark Miller

Reputation: 7447

I might do it using the new array_column()(requires PHP >= 5.5) and array_walk().

The good 'ol foreach loop should be fine, or you could just pull them out directly assuming you know what is in the array all the time. But here's something I think is a little fancier ;) ...

$arr = array_column($array, 'value', 'name');

array_walk($arr, function(&$v, $k) use (&$telephone, &$city){
    if ($k == 'infotel') $telephone = $v;
    elseif ($k == 'location') $city = $v;
});

echo $telephone; //+39080123456
echo $city;      //Bari

See Demo - updated updated updated

Upvotes: 1

Karan Thakkar
Karan Thakkar

Reputation: 1467

you can create a function for that.

function custom_search($search_for='',$search_in=array())
{
  if($search_for=='' OR empty($search_in)) return '';
    foreach($search_in as $val)
    {
       if($val['name']==$search_for) {return $val['value'];}
    }
  return '';
}
$telephone=custom_search("infotel",$array);

Upvotes: 3

Manwal
Manwal

Reputation: 23816

$telephone='';
$location='';
foreach($array as $k=>$v)
{
   if($v['name']=="infotel") 
   {
     $telephone=$v['value'];
     break;
   }
   if($v['name']=="location") 
   {
     $location=$v['value'];
     break;
   }
}
echo $telephone; 
echo $location;

Upvotes: 0

Shairyar
Shairyar

Reputation: 3356

$array = array(
    array('name' => 'infotel', 'value' => '+39080123456' ),
    array('name' => 'location', 'value' => 'Bari')
);

$telephone = $array[0]['value'];
$city = $array[1]['value'];
echo $telephone;

echo $city;

Upvotes: 0

pavel
pavel

Reputation: 27092

If you have only this array, use:

$tel = $array[0]['value'];
$loc = $array[1]['value'];

Upvotes: 0

Related Questions