Home > Net >  Exploding an array values within a foreach loop in PHP
Exploding an array values within a foreach loop in PHP

Time:05-29

Think I have an array like this,

$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];

So, then I want to explode above array values using / and if explode array have 3 elemens, then I need to create a new array like this.

$prefixes = ['PO', 'XY','PO'];

Can I know what is the better and efficient approach to do this.

This is what I have sofar:

$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];


foreach ($code as $v) {
    $nwCode = explode("/",$v);
    if(count($nwCode) == 3) {
      $nwAry[] = $newCode[0];
    }
    
    $nwCode = [];
}

echo '<pre>',print_r ($nwAry).'</pre>';

CodePudding user response:

$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];

$prefixes = array_map(function($e){
  $nwCode = explode('/', $e);
  if(count($nwCode) == 3)
  {
    return $nwCode[0];
  }
} ,$code);

$prefixes = array_filter($prefixes, function($e){ if(strlen($e) > 0) return true; });

echo "<pre>";
var_dump($prefixes);
echo "</pre>";

The array_map used to get those prefixes, while array_filter to remove the empty prefixes from the unmatching items.

You could use array_reduce too.

$prefixes = array_reduce($code, function($carry, $item){
  $nwCode = explode('/', $item);
  if(count($nwCode) == 3)
  {
    array_push($carry, $nwCode[0]);
  }
  return $carry;
}, array());
  • Related