0

I have the following PHP code and would like to split the string into separate variables:

$names = "login1,login2,login3,login4,...loginN";

Example result:

$login1 = "login1";

$login2 = "login2";

$login3 = "login3";

$login4 = "login4";
2

2 Answers 2

6
foreach (explode(',', $names) as $name) {
    $$name = $name;
}

But really, why in the world do you want to do this?

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

6 Comments

Thats really new to me and really weird syntax.
+1 for answer, but also agree with the questioning of "Why?" -- wouldn't an array be better?
// Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 in this script how to echo all what in $pizza like echo $pieces[0]; echo $pieces[1]; echo $pieces[2]; ...
@Narek Use foreach! In my example I'm showing you how to use it. Just echo $name instead of assigning it.
|
0

If a more flexible extraction was needed then you could utilize regular expressions via preg_split():

foreach(preg_split('/,/', $names) as $login){
    $$login = $login;
};

Comments

Your Answer

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