Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Returning two values from a function in PHP
In PHP, you cannot directly return two variables from a function, but you can achieve this by returning them in an array or using other data structures. This approach allows you to return multiple values and access them efficiently.
Method 1: Using Indexed Array
The most common approach is to return an array containing the values −
<?php
function getNameAndAge() {
$name = "John";
$age = 25;
return array($name, $age);
}
// Get the returned array
$result = getNameAndAge();
echo "Name: " . $result[0] . "<br>";
echo "Age: " . $result[1] . "<br>";
?>
Name: John Age: 25
Method 2: Using Associative Array
For better readability, use associative arrays with meaningful keys −
<?php
function calculateAreaAndPerimeter($length, $width) {
$area = $length * $width;
$perimeter = 2 * ($length + $width);
return array(
'area' => $area,
'perimeter' => $perimeter
);
}
$dimensions = calculateAreaAndPerimeter(5, 3);
echo "Area: " . $dimensions['area'] . "<br>";
echo "Perimeter: " . $dimensions['perimeter'] . "<br>";
?>
Area: 15 Perimeter: 16
Method 3: Using list() for Assignment
You can use list() to assign returned array values to individual variables −
<?php
function getDivisionResult($dividend, $divisor) {
$quotient = intval($dividend / $divisor);
$remainder = $dividend % $divisor;
return array($quotient, $remainder);
}
// Using list() to assign values directly
list($quotient, $remainder) = getDivisionResult(17, 5);
echo "Quotient: " . $quotient . "<br>";
echo "Remainder: " . $remainder . "<br>";
?>
Quotient: 3 Remainder: 2
Comparison
| Method | Advantages | Best Use Case |
|---|---|---|
| Indexed Array | Simple, compact | When order is obvious |
| Associative Array | Self-documenting, clear | When meaning matters more than order |
| list() Assignment | Direct variable assignment | When you need separate variables immediately |
Conclusion
Returning multiple values in PHP is best achieved using arrays. Choose indexed arrays for simple cases, associative arrays for clarity, and list() assignment for direct variable extraction based on your specific needs.
Advertisements
