dy4biw
Last Updated: February 25, 2016
·
327
· raphaelstolt

'Lean out' an array w/out using a loop

php

In case you have to reduce an array structure you can use an anonymous callback function instead of a traditional foreach loop.

<?php
$sts = array(
    array('id' => 100, 'slot' => 'a'),
    array('id' => 200, 'slot' => 'b'),
    array('id' => 300, 'slot' => 'c'),
    array('is' => 400, 'slot' => 'd'),
);
$stis = array();
array_filter($sts, function($st) use(&$stis) {
    if (isset($st['id'])) {
        return $stis[] = $st['id'];
    }
});

And the result will be the following w/ one omitted element which fails the guard-clause embeded in the anonymous function:

array(3) {
  [0] =>
  int(100)
  [1] =>
  int(200)
  [2] =>
  int(300)
}