Sol Sol - 21 days ago 5
PHP Question

foreach key -> value outside foreach

How can I access specific 'keys' and their associated 'values' for use later outside of the foreach loop?

Here's the array;

Array ( [0] =>
CustomFields
[1] => stdClass Object
( [Key] => Phone [Value] => 5555555 )
[2] => stdClass Object
( [Key] => City [Value] => New York)
[3] => stdClass Object
( [Key] => State [Value] => NY)
[4] => stdClass Object
( [Key] => Cellphone [Value] => 222444555 )


And here's the query I'm using;

$cf = array();
foreach($result->response->CustomFields as $data) {

$cf [] = $data;

if ($cf [] = ($data->Key == 'Phone' ) ) {
echo 'Your Phone number is:'.$data->Value.'<br> ';
}

if ($cf [] = ($data->Key == 'City' ) ) {
echo 'Your City is: '.$data->Value.'<br> ';
}
}


My query works inside the foreach loop and correctly prints the Phone and City value - but I would like to be able to print these values outside of this loop.

Answer
function findByKeyInCollection($key, $collection){
    foreach($collection as $data) {
         if ($data->Key == $key) {
             return $data;
         }
    }
}
$phone = findByKeyInCollection("Phone", $result->response->CustomFields);
echo 'Your Phone number is:'.$phone->Value.'<br> ';