1
$arr_ramones = array(
          1=>array('name'=>'johnny', 'display'=>1), 
          2=>array('name'=>'joey', 'display'=>1), 
          3=>array('name'=>'cj', 'display'=>0), 
          4=>array('name'=>'deedee', 'display'=>1), 
          5=>array('name'=>'marky', 'display'=>0)
  );

I'd like to loop through my array but only with rows that have a display value of 1.

I read how to do this with a regular array. Can something similar be done with multidimensional arrays without costing performance? My example array is small - real world example contains thousands of values.

a coder
  • 7,530
  • 20
  • 84
  • 131
  • 1
    If the 'real world' example array would contain `thousands of values` then really it should be held in a database, you would then be able to filter them as they are requested from the DB. – AeroX Apr 02 '14 at 15:39

4 Answers4

2

also works with array_filter.

$arr_ramones = array(
    1 => array('name'=>'johnny', 'display'=>1), 
    2 => array('name'=>'joey', 'display'=>1), 
    3 => array('name'=>'cj', 'display'=>0), 
    4 => array('name'=>'deedee', 'display'=>1), 
    5 => array('name'=>'marky', 'display'=>0)
);
$filter = array_filter($arr_ramones, function($arr) {
    return $arr['display'] == 1;
});
hsz
  • 148,279
  • 62
  • 259
  • 315
Simon Wicki
  • 4,029
  • 4
  • 22
  • 25
1

Just try with:

foreach ($arr_ramones as $item) {
  if ($item['display']) {
    echo $item['name'];
  }
}

or use array_filter

$display = array_filter($arr_ramones, function($item){
  return $item['display'];
});

foreach ($display as $item) {
  echo $item['name'];
}
hsz
  • 148,279
  • 62
  • 259
  • 315
1

Try array_walk if you just want to display data without creating new array. In case of creating array use array_map

array_walk($arr_ramones, function($a) { // displaying information from array based on requirements
    if ( $a['display'] == 1) {
        echo $a['name'] . " "; // johnny joey deedee 
    }
});

$n = array_map(function($a) { // creating new array based on requirements
    if ( $a['display'] == 1) {
        return $a['name'];
    }
}, $arr_ramones);
nanobash
  • 5,419
  • 7
  • 38
  • 56
  • Is there a performance benefit in using `array_walk` as opposed to `foreach`? – a coder Apr 02 '14 at 15:47
  • @acoder With performance they are pretty much the same while this function's algorithm uses loop as well, though it has another benefits. See [this](http://stackoverflow.com/questions/3432257/difference-between-array-map-array-walk-and-array-filter) – nanobash Apr 02 '14 at 15:51
0

A simple foreach like this.

foreach($arr as $k=>$arr)
{
 if($arr['display']==1)
  {
    echo $arr['name']."<br>";
  }
}

Using an array_filter

function filt($var)
{
   return $var['display']==1;
}  

$new_arr=array_filter ($arr_ramones,"filt" );
print_r($new_arr);

Demo

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126