OK basically lets say i have an array like this: $items = array( [0] => 2 [1] => [2] => [3] => [4] => [5] => 2 [6] => 2 [7] => [8] => 2 [9] => [10] => [11] => 1 [12] => 1\' [13] => 1 [14] => [15] => [16] => [17] => [18] => [19] => ) you can see that only some of the keys have values, now when i use this for each statement it shows all of the values in the key. where as i only want to display the ones with values in foreach($items as $key => $value){ echo '<div class="test" style="background: yellow; margin: 30px;">'; echo "<br /> Item ID: $value <br />"; echo '</div>'; } if anyone could help it would be very much appreciated
foreach($items as $key => $value){ if (strlen($value)<1){ echo '<div class="test" style="background: yellow; margin: 30px;">'; echo "<br /> Item ID: $value <br />"; echo '</div>'; } }
There are so many array functions in php, so let's use them: function myfilter($s){ return trim($s)!=''; } function mymap($s){ return '<div class="test" style="background: yellow; margin: 30px;"><br /> Item ID: '.$s.' <br /></div>'; } $items = array(0 => '2',1 => '',2 => '',3 => '',4 => '',5 => '2', 6 => '2', 7 => '', 8 => '2',9 => '',10 => '',11 => '1',12 => '1', 13 => '1',14 => '',15 => '',16 => '', 17 => '',18 => '',19 => ''); echo implode('',array_map('mymap',array_filter(array_unique($items),'myfilter'))); PHP: I'm using array_unique() because it seems that this "Item ID" must be unique. Regards
As an alternative to mattinblack's solution you can also use the empty construct to check if the key contains an empty value... e.g. foreach($items as $key => $value){ if (!empty($value)){ echo '<div class="test" style="background: yellow; margin: 30px;">'; echo "<br /> Item ID: $value <br />"; echo '</div>'; } } PHP: