I am using PHP. I would like to use foreach function and check if two subarrays do exist. How can I check whether or not subarrays [1] and [2] do exist? As you see here, [1] does exist but [2] does not. Array ( [65] => Array ( [1] => Array ( ) ) ) PHP:
Here: <?php $test = [ 65 => [ 1 => 'something', 2 => 'something else', ], ]; if (is_array($test[65])) { foreach ($test[65] as $key => $value) { echo $key.' exist'; } } PHP:
Thanks! How should I modify the foreach loop if I want to create [65][1] and/or [65][2] if they do not exist?
You can't, because the foreach-loop will only read the actual, existing elements. You will have to something else if that's what you want. You could use a for-counter with a predetermined counter and check if the key exists. Something like: for ($c = 1; $c <=2; $c++) { if (array_key_exists($c,$test[65])) { echo 'test[65]['.$c.'] exist'; } else { $test[65][$c] = 'content goes here'; } } Code (markup):
I'm trying to read between the lines and see what you're really up to. $test = [ 65 => [ 'sizes' => array('s','m','l'), 'colours' => array('red','blue','yellow') ], ]; foreach($test as $k => $arr){ if (!array_key_exists('sizes', $arr){ $test[$k]['sizes'] = array('OSFA'); } if (!array_key_exists('colours', $arr){ $test[$k]['colours'] = array('black'); } PHP: and if that's on the right track you can also do this $test = [ 65 => [ 'sizes' => ['s','m','l'], 'colours' => ['red','blue','yellow'] ], ]; $defaults = array[ 'sizes' => ['OSFA'], 'colours' => ['black'] ] foreach($test as $k1 => $arr){ foreach($defaults as $k2 => $defs) { if (!array_key_exists($k2, $arr){ $test[$k][$k2] = $defs; } } PHP: