This question is an excellent opportunity to demonstrate a better way.
Code: (Demo: https://3v4l.org/dU09B )
$currencies = [
'mxn' => [
'sign' => '$',
'plans' => [
'tiny' => 429,
'small' => 1319,
'medium' => 3399,
'big' => 6669
]
],
'usd' => [
'sign' => '$',
'plans' => [
'tiny' => 29,
'small' => 319,
'medium' => 399,
'big' => 669
]
]
];
$currency='mxn';
if(!isset($currencies[$currency])){
echo "$currency was not found in the currencies array.";
}else{
echo "In $currency:\n";
foreach($currencies[$currency]['plans'] as $size=>$price){
echo "\t$size costs {$currencies[$currency]['sign']}$price\n";
}
}
Output:
In mxn:
tiny costs $429
small costs $1319
medium costs $3399
big costs $6669
Explanation:
Because the currency names will logically be unique, you can reduce the overall size of your lookup array by declaring the currency names as subarray keys.
If you were to store this same data in a database, you would assign the currency name as the Primary Key.
As a matter of improved efficiency and direct coding, the new array structure will allow you to swiftly determine if your desired currency exists in the multi-dimensional array using isset()
.
Your question title asks: Loop into an array if I have a key in PHP I take this to mean that it is possible that the needle may not be in the haystack. Maybe this is not what you mean, but this consideration is important to build into your code.
Verifying that the key exists in the multidimensional array is essential (to avoid a Notice ftom php) before attempting to use the key.
If you are not able or interested in modifying your data structure, then be sure that you employ two pieces of best practice:
break
your searching foreach
loop after your currency is found; or call array_search()
which does this for you. Iterating the remaining items in your array after you've received the desired data is wasteful/inefficient.
Write a condition that handles the possibility of the currency not being found. Because trying to access: $currencies[false]
isn't going to work out well for you.