0

I have two strings containing values separated by comma and space.

Example: String 1 = France, Germany, Italy; String 2 = Belgium, Netherlands What I want is create an array in PHP that contains all values from both strings and sorted alphabetically. So in this case the output should be an array with the following values and order: Belgium,France,Germany,Italy,Netherlands.

I tried the following but this doesnt work. Can anyone tell me how I can achieve this ? I saw that I need to explode the single strings first as otherwise it seems to treat all values from one string as just one value and then the sorting doesnt work.

$countries = array();
$input1 = explode(", ", "France", "Germany", "Italy"); //hard-coded for testing
$input2 = explode(", ", "Belgium", "Netherlands"); //hard-coded for testing
foreach($input1 as $key => $val) {
    array_push($countries, $input1);
}
foreach($input2 as $key => $val) {
    array_push($countries, $input2);
}
sort($countries);

Many thanks for any help with this, Mike.

2
  • explode(", ", "France","Germany","Italy"); <--- what's this? Have you checked the php.net/explode ? Commented Apr 30, 2014 at 21:43
  • 1
    $countries = array_merge(explode(",", "France,Germany,Italy"),explode(",", "Belgium,Netherlands")); sort($countries); Commented Apr 30, 2014 at 21:45

3 Answers 3

1
$input1 = explode(", ", "France, Germany, Italy"); 
$input2 = explode(", ", "Belgium, Netherlands"); 
$countries = array_merge($input1, input2);
var_dump(sort($countries));

Check the string => "France","Germany","Italy" != "France, Germany, Italy"

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is misleading. var_dump() will print true.
1
foreach ($input2 as $input){
  $countries[]=$input;
}

sort($countries);

Comments

1

Use array_merge

$input1 = explode(",", "France,Germany,Italy"); //hard-coded for testing
$input2 = explode(",", "Belgium,Netherlands"); //hard-coded for testing

$countries = array_merge($input1, $input2)
sort($countries);

Or join the strings 1st

$input1 = "France,Germany,Italy"; 
$input2 = "Belgium,Netherlands";

$countries = explode(",", $input1 . "," . $input2);
sort($countries);

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.