Home > Article > Backend Development > How does a PHP function return an array?
PHP functions can return arrays by using the return statement: Return a simple array: return ['value', 'value', 'value']; Return an associative array: return ['key' => 'value', 'key ' => 'value']; Dynamically return an array based on parameters: return ['key' => calculated value, 'key' => calculated value];
##How does a PHP function return an array?
In PHP, a function can return an array by using thereturn statement. Let’s explore how this is done through some practical examples.
Example 1: Return a simple array
function getStates() { return ['Alabama', 'Alaska', 'Arizona', 'Arkansas']; } $states = getStates(); print_r($states);This will output an array containing the states of the United States.
Example 2: Returning an associative array
function getUserInfo($userId) { // 模拟从数据库获取用户数据 return [ 'id' => $userId, 'name' => 'John Doe', 'email' => 'johndoe@example.com' ]; } $userInfo = getUserInfo(123); echo $userInfo['name']; // 输出:John DoeThis will return an associative array containing the user details.
Example 3: Return a dynamic array using the parameters of the function
function calculateDiscount($price, $discountPercentage) { $discountAmount = $price * ($discountPercentage / 100); return ['discount_amount' => $discountAmount, 'final_price' => $price - $discountAmount]; } $discountInfo = calculateDiscount(100, 20); echo $discountInfo['final_price']; // 输出:80This function dynamically returns an array based on the parameter value.
The above is the detailed content of How does a PHP function return an array?. For more information, please follow other related articles on the PHP Chinese website!