0

I am learning some php right now. Is there a way to define a variable with multiple variables?

Something like:

$name = "John"
$lastname = "Doe"
$number = "017434234"

$user = $name,$lastname,$number

Of corse this script does not work. Which is the correct way?

6
  • As an array? $user = [$name,$lastname,$number]; var_dump($user);? Commented Sep 2, 2015 at 9:57
  • Concat them. $user = $name.$lastname.$number; Commented Sep 2, 2015 at 9:58
  • Depends, what are you trying to do? Defining a variable with multiple variables does not mean much. You want to concatenate them? Create an array? Commented Sep 2, 2015 at 9:59
  • add semicolon at the end of variable deceleration and concate them using $user = $name.",".$lastname.",".$number; Commented Sep 2, 2015 at 9:59
  • Are you learning PHP, or are you learning programming at all? Because you should have a basic knowledge of programming structures. Like arrays. Commented Sep 2, 2015 at 10:01

2 Answers 2

1

If you want to put them together, the dot concatenates the variables:

$user = $name.$lastname.$number;

If you want to define multiple strings, you can use an array:

$user = ["John", "Doe", "123"];

Or you can use keys in your array to give them meaning:

$user = [firstname => "John", lastname => "Doe"];
echo $user->firstname; //gives John
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! That was quite easy :-)
... or build a User class instead of an associative array for structured objects
0

Awesome that youre learning PHP :)

You can make it an array like this whit a function, of course.. this is a little more "over complicated" than the example above.

Script:

//Function array with inputting and selecting what to return:
function MyArray($Firstname, $Lastname, $Number, $OutPutWhat){

   //Create an array:
   $Array = array(
       'FirstName' => "$Firstname",
       'LastName' => "$Lastname",
       'Number' => "$Number"
   );
       //Return the arrayValue[ofthis]
       return $Array[$OutPutWhat];
}

 //Echo out the value
echo MyArray("John", "Doe", "1234567", 'FirstName');  //Outputs the firstname

Comments

Your Answer

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