2

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.

1
  • First of all i dont think you can do stripos in if statement, cause its returning mixed type, not bool (lets say its in 0 position then it will be false, like in your example) 2nd problem is that even if you find 'Samsung' you still need to find 'Galaxy' with your code Commented Jul 10, 2015 at 8:35

3 Answers 3

3

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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Could be simpler,

$phones = ['Apple iPhone 4','Apple iPhone 5','Samsung Galaxy S6'];

$final = [];

foreach($phones as $phone)
{
    $brand_name = strtok($phone, " ");
    $final[$brand_name][] = trim(strstr($phone, " "));
}

Dump of $final,

array (size=2)
  'Apple' => 
    array (size=2)
      0 => string 'iPhone 4' (length=8)
      1 => string 'iPhone 5' (length=8)
  'Samsung' => 
    array (size=1)
      0 => string 'Galaxy S6' (length=9)

Comments

0

You only need to call one function while looping if you limit the space-splitting to 1 explosion. For concise syntax in the loop body, use array destructuring to push data into the grouped result array.

Code: (Demo)

$result = [];
foreach ($phones as $item) {
    [$key, $result[$key][]] = explode(' ', $item, 2);
}
var_export($result);

Or array_reduce() if you prefer functional code styling. (Demo)

var_export(
    array_reduce(
        $phones,
        function($result, $item) {
            [
                $key,
                $result[$key][]
            ] = explode(' ', $item, 2);
            return $result;
        },
    )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.