1

Basically I want to split an array element if it contains a comma, and preserve element order within the array.

So I have an element like this:

$array = ["coke", "joke", "two,parts", "smoke"];

And I want to turn it find the one with the comma, split it by the comma into two separate elements and maintain order as if nothing had happened.

This is the desired result:

$array = ["coke", "joke", "two", "parts", "smoke"];
0

4 Answers 4

3

Hope this will be helpful, here we are using foreach and explode to achieve desired output.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$array = ["coke", "joke", "two,parts", "smoke"];
$result=array();
foreach($array as $value)
{
    if(stristr( $value,","))
    {
        $result=  array_merge($result,explode(",",$value));
    }
    else
    {
        $result[]=$value;
    }
}
print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

2

Short and sweet: let's use array_reduce() with the array being reduced to an array:

$arr = ["coke", "joke", "two,parts", "smoke"];
function filter($v1,$v2)
{
   return array_merge($v1,explode(',',$v2)); 
}
print_r(array_reduce($arr,"filter",[]));

No explicit iterating nor temporary variables, needed!

Comments

1

This is the shortest, sweetest method. Simply join all of the elements into a comma-separated string, then split the string on every comma back into an array.

This will be the most efficient method as it will never make more than two function calls in total. The other answers use one or more function calls on each iteration of the input array which only slows the process down.

Also, using a case-insensitive strstr() call on a comma makes no logical sense. The PHP manual even has a special Note saying not to use strstr() for needle searching.

Code: (Demo)

$array = ["coke", "joke", "two,parts", "smoke"];
var_export(explode(',', implode(',', $array)));

Output:

array (
  0 => 'coke',
  1 => 'joke',
  2 => 'two',
  3 => 'parts',
  4 => 'smoke',
)

Comments

-2

Create new array which will have fixed values. Then iterate trough original array and explode each element and append it to new array.

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.