PHP Core / Functions / Function return a value
Function return
-
Function return
1. In the previous topics, we have learned how to create a function, pass data to a function and echo the result inside the function.
2. Sometimes we need to return the result of data instead of 'echo' statement
3. using 'return' statement at the end of the function for returning data to the function caller
"manoj", "mark" => 90]; $student2 =["name" => "anu", "mark" => 60]; $student3 =["name" => "hari", "mark" => 80]; //define function function findGrade($marks){ if ($marks>=60) { $grade = "First Division"; } else if($marks>=45) { $grade = "Second Division"; } else if($marks>=33) { $grade = "Third Division"; } else { $grade = "Fail"; } return $grade; } // function call and show the result ?> 1. We don't use php logic or function call between the html tags.
2. We should use all logics and function calls inside the logical part of the coding.
3. We use only the variables inside or between the html tags for showing or presenting the data.
-
Better Solution : Call the function in the php logical part and store the result in a variable
"manoj", "mark" => 90]; $student2 =["name" => "anu", "mark" => 60]; $student3 =["name" => "hari", "mark" => 80]; //define function function findGrade($marks){ if ($marks>=60) { $grade = "First Division"; } else if($marks>=45) { $grade = "Second Division"; } else if($marks>=33) { $grade = "Third Division"; } else { $grade = "Fail"; } return $grade; } //function call and store the return result in a variable $student1['grade'] = findGrade($student1['mark']); $student2['grade'] = findGrade($student2['mark']); $student3['grade'] = findGrade($student3['mark']); //show the result in the html area ?>