Change language

How to return multiple values ​​from a function in PHP?

|
Example 1:This example shows how to return multiple values ​​from a function in PHP. First create an empty array and finally place the element in the array, then return the array.  
// Function for returning an array
// factors p function factors ( $n ) { // Declare an empty array $fact = array (); // Loop to find for ( $i = 1; $i < $n ; $i ++) { // Check if I am a factor // n then put it in an array if ( $n % $i == 0) array_push ( $fact , $i ); } // Return array return $fact ; }  
// Declare a variable and initialize it $num = 24;  
// function call $nFactors = factors ( $num );  
// Show result echo ’Factors of’ . $num . ’are:
; foreach ( $nFactors as $x ) { echo $x . "
"
; }  
?>
Exit:
Factors of 24 are: 
1
2
3
4
6
8
12
Example 2: B In this example, the list function is used to store the variable value being changed. It is used to assign array values ​​to multiple variables at the same time. Multiple values ​​returned in an array from a function can be assigned to the corresponding variables using list().  
// Function to replace two numbers function swap ( $x , $y ) { return array ( $y , $x ); }  
// Declare a variable and initialize it $a = 10; $b = 20; echo ’ Before swapping the elements
;  
// Show the values ​​of a and b echo ’a =’ . $a .
. ’b =’ . $b .
;  
// call a function to replace the values ​​a and b list ( $a , $b ) = swap ( $a , $b ); echo ’ After swapping the elements
;  
// Show the values ​​of a and b echo ’a =’ . $a .
. ’b =’ . $b .
;  
?>
Exit:
Before swapping the elements 
a = 10
b = 20
After swapping the elements
a = 20
b = 10
SO 1 data error