Skip to content
Advertisement

Split array of strings on first space and make new array grouping by first word

I have the following array:

$phones = array(
  [0] => Apple iPhone 4
  [1] => Apple iPhone 5
  [2] => Samsung Galaxy S6
)

What I’d like to do is split this array up, separating the brand from the model of phone, so in the end I can build an array that would give me this:

$phone_array = array (
  'Apple' => array (
      'iPhone 4', 'iPhone 5'
  ),
  'Samsung' => array (
      'Galaxy S6',
  )
)

So far, I have the following unfinished code:

$brand_dictionary = "/(samsung|apple|htc|sony|nokia)/i";
foreach($phones as $p) {
    if(stripos($p,$brand_dictionary)) {
        pr($p);
        die();
    }
}

But this isn’t working correctly at all.

Advertisement

Answer

Try with –

$phones = array(
  'Apple iPhone 4',
  'Apple iPhone 5',
  'Samsung Galaxy S6'
);

$new = array();

foreach($phones as $phone) {
  $temp = explode(' ', $phone);
  $key = array_shift($temp);
  $new[$key][] = implode(' ', $temp); 
}

var_dump($new);

Output

array(2) {
  ["Apple"]=>
  array(2) {
    [0]=>
    string(8) "iPhone 4"
    [1]=>
    string(8) "iPhone 5"
  }
  ["Samsung"]=>
  array(1) {
    [0]=>
    string(9) "Galaxy S6"
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement