-7

Input:

$string="cat, dog, pig, hello";

Required output (dynamically)

$string1= cat;
$string2= dog;
$string3= pig;
$string4= hello;

After the use of a comma in the string, the word become a new sub string.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • Use an array instead of numbered variables..... esspecially when you have to keep track of how many numbered variables you have, your code becomes excessively complicated – Mark Baker Jun 13 '16 at 08:48

3 Answers3

2

Try this:

$string="cat, dog, pig, hello";
$arr = explode(", ",$string);
foreach($arr as $key=>$array) {
 $key = 'string'.($key+1);
 ${$key} = $array;
}
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Rizier123 Jun 13 '16 at 12:11
1

Make use of extract function in PHP

$string="cat, dog, pig, hello";

$stringArr = explode(",", $string); //Split strings to array using delimeter (,)

$newArr = [];
foreach ($stringArr as $key => $value) {
    $newArr['string'.($key+1)] = trim($value); //Use trim to remove the unwanted spaces in your words after exploding
}

extract($newArr);

echo $string1; //cat
echo $string2; //dog
echo $string3; //pig
echo $string4; //hello

Remember: You end up creating too many variables!! It is better to use array as array

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
0
    $string="cat, dog, pig, hello";
     $Array = explode(',', $string);
    print_r($Array );
User2403
  • 317
  • 1
  • 5