Home  >  Article  >  Backend Development  >  How does a PHP function return an array?

How does a PHP function return an array?

WBOY
WBOYOriginal
2024-04-11 08:00:021047browse

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];

PHP 函数如何返回数组?

##How does a PHP function return an array?

In PHP, a function can return an array by using the

return 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 Doe

This 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']; // 输出:80

This 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn