How does a PHP function return an array?

WBOY
Release: 2024-04-11 08:00:02
Original
1036 people have browsed it

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);
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!