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.
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.
Try this:
$string="cat, dog, pig, hello";
$arr = explode(", ",$string);
foreach($arr as $key=>$array) {
$key = 'string'.($key+1);
${$key} = $array;
}
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
$string="cat, dog, pig, hello";
$Array = explode(',', $string);
print_r($Array );