Parsing Multidimensional Associative Arrays
It can be frustrating when you’re learning something new – you get stuck on what seems like an arguably simple task, such as parsing through an array. Multidimensional associative arrays are certainly different than your regular array, but parsing through them is just as simple (if not more-so).
Let’s take this array for example:
Array (
['stringIndex1'] = "value1",
['stringIndex2'] = "value2",
['stringIndex3'] = "value3",
['stringIndex4'] = "value4"
)
Okay, so we want to parse through this array, but we can’t use the traditional for()
loop. To do this we’re going to use the foreach()
loop. If you’re unfamiliar with foreach()
, it’s a loop that can parse through arrays without requiring an incremented numerical value. So, let’s parse:
foreach ($ourArray as $key=>$val) {
echo $key . " : " . $val . "<br />";
}
It’s a pretty simple example that will print out the $key
and the $val
for each array row. So, the output would be:
stringIndex1 : value1
stringIndex2 : value2
stringIndex3 : value3
stringIndex4 : value4
It’s that simple. If the $val
were another array, you can run a nested foreach()
loop – as many levels as you need:
foreach ($ourArray as $key=>$val) {
// do something here
foreach ($val as $key2=>$val2) {
// do something here too
}
}
Multidimensional associative arrays are incredibly useful when you’re programming, and now you know how to parse through them.