Custom functions in PHP can return values of specified types through the return statement, including strings, numbers, arrays, and objects. Practical case: - Return string: function greet($name) { return "Hello, $name!"; } - Return array: function get_user_data($id) { return ["name" => "John", "email " => "john@example.com"]; }
How to return the value of a custom function in PHP?
In PHP, custom functions can return values of specified types. You can use the return
statement to return a value, and the return value can be of various types, including strings, numbers, arrays, and objects.
Syntax:
function function_name(...$parameters): return_type { // 函数体 return $value; }
Where:
is the name of the function.
is an optional parameter list.
is the type of value returned by the function.
is the
return statement, used to specify the function return value.
Practical case:
The following is an example of a custom function that returns a string:function greet($name) { return "Hello, $name!"; } $greeting = greet("John"); echo $greeting; // 输出: Hello, John!
function get_user_data($id) { $data = [ "name" => "John", "email" => "john@example.com", ]; return $data; } $user_data = get_user_data(1); echo $user_data["name"]; // 输出: John
Tip:
value.
keyword to specify that a function will not return any value.
The above is the detailed content of How to return the value of a PHP custom function?. For more information, please follow other related articles on the PHP Chinese website!