1

Is there any way I can explode the array values of a big array without iterating through each item?

For e.g. I have

$Array = [
    'Foo and Bar',
    'Bar and Baz',
    'Baz and Foo'
];

I want

$Array1 = [
    'Foo',
    'Bar',
    'Baz'
];
$Array2 = [
    'Bar',
    'Baz',
    'Foo'
];

I can achieve this by simply doing a foreach loop. Like this

foreach ($Array as $Value) {
    $DataEx = explode(' and ', $Value);
    $Array1[] = $DataEx[0];
    $Array2[] = $DataEx[1];
}

I have came across answers where some iteration is being suggested. But I seek to know if it can be achieved by any array function of PHP or by any combination of such array functions.

Donnie Ashok
  • 1,355
  • 1
  • 11
  • 26

2 Answers2

1

Here's an approach without a "foreach" loop in your code.

$array = [
  'Foo and Bar',
  'Bar and Baz',
  'Baz and Foo'
];

$explodedArray = array_map( function( $v ){ return explode( ' and ', $v ); }, $array );

$Array1 = array_column( $explodedArray, 0 );
$Array2 = array_column( $explodedArray, 1 );
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
1

You can use array_walk

$Array = [
    'Foo and Bar',
    'Bar and Baz',
    'Baz and Foo'
];

$return = [];
array_walk($Array, function($v) use(&$return){
    list($return['Array1'][], $return['Array2'][]) = preg_split('/\s+and+\s/i', $v);
});
extract($return);

demo : https://paiza.io/projects/gGYT_UfojR9odDc7KoHOHg

Output

// Array1
$Array1 = [
    'Foo',
    'Bar',
    'Baz'
];

// Array2
$Array2 = [
    'Bar',
    'Baz',
    'Foo'
];
Anfath Hifans
  • 1,588
  • 1
  • 11
  • 20