In PHP, assigning multiple variables in one line can be a handy and efficient way to streamline your code. This technique not only makes your code more concise but also improves readability. There are several approaches to achieve this, each with its own syntax and use cases.
Table of Content
Using Multiple Assignment
PHP allows multiple variables to be assigned the same value in a single line.
<?php $a = $b = $c = 10;
echo "a = $a, b = $b, c = $c" ;
?> |
a = 10, b = 10, c = 10
Using list() Function
The list() function is a versatile way to assign multiple variables at once. It allows you to assign values from an array to individual variables in a single line.
<?php list( $var1 , $var2 , $var3 ) = array ( 'apple' , 'banana' , 'cherry' );
echo "$var1, $var2, $var3\n" ;
$data = [10, 20, 30];
list( $a , $b , $c ) = $data ;
echo "$a, $b, $c" ;
?> |
apple, banana, cherry 10, 20, 30
Using explode() Function
The explode() function is useful when dealing with delimited strings. It splits a string into an array based on a specified delimiter and assigns the values to variables.
<?php $str = "Geeks, Noida, +91-9876543210" ;
list( $name , $address , $mobile ) = explode ( ',' , $str );
echo "$name, $address, $mobile" ;
?> |
Geeks, Noida, +91-9876543210
Using Short Array Syntax
PHP 5.4 introduced a short array syntax, making it more convenient to assign multiple variables in a single line.
<?php [ $var1 , $var2 , $var3 ] = [ 'apple' , 'banana' , 'cherry' ];
echo "$var1, $var2, $var3" ;
?> |
apple, banana, cherry