
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Returning Two Values from a Function in PHP
Two variables can’t be explicitly returned, they can be put in a list/array data structure and returned.
Example
function factors( $n ) { // An empty array is declared $fact = array(); // Loop through it for ( $i = 1; $i < $n; $i++) { // Check if i is the factor of // n, push into array if( $n % $i == 0 ) array_push( $fact, $i ); } // Return array return $fact; } // Declare a variable and initialize it $num = 12; // Function call $nFactors = factors($num); // Display the result echo 'Factors of ' . $num . ' are: <br>'; foreach( $nFactors as $x ) { echo $x . "<br>"; }
Output
This will produce the following output −
Factors of 12 are: 1 2 3 4 6
Advertisements