Open In App

How to Assign Multiple Variables in One Line in PHP ?

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Using Multiple Assignment

PHP allows multiple variables to be assigned the same value in a single line.

PHP




<?php
    
$a = $b = $c = 10;
  
echo "a = $a, b = $b, c = $c";
  
?>


Output

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




<?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";
?>


Output

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




<?php
  
$str = "Geeks, Noida, +91-9876543210";
list($name, $address, $mobile) = explode(',', $str);
  
echo "$name, $address, $mobile";
  
?>


Output

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




<?php
  
[$var1, $var2, $var3] = ['apple', 'banana', 'cherry'];
  
echo "$var1, $var2, $var3";
  
?>


Output

apple, banana, cherry


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads