search
HomeBackend DevelopmentPHP TutorialHow to return multiple values ​​from one PHP function
How to return multiple values ​​from one PHP functionAug 27, 2023 pm 02:05 PM
php functionReturn multiple values

How to return multiple values ​​from one PHP function

We mainly use function parameters to obtain external data inside the function for further processing. Similarly, we return values ​​from PHP functions to access processed data outside the function. You can define functions in PHP with or without return values.

Although a function in PHP can have multiple parameters, it is impossible to have multiple return statements. In this tutorial, I will show you how to return multiple values ​​from a function in PHP.

  • Return statement in PHP
  • Use an array to return multiple values
  • Use objects to return multiple values

Return statement in PHP

Functions in PHP can have an optional return statement. When called from within a function, the return statement immediately stops the execution of any further code. This also includes other return statements. Here is an example:

<?php

function multiple_returns($a, $b) {
    $x = 2*$a;
    $y = 3*$b;

    return $x;

    if($y%3 == 0) {
        echo "Y is: ".$y;
    }

    return $y;
}

$m = 0;
$n = 0;

$m = multiple_returns(5, 18);

// list($m, $n) = multiple_returns(5, 18);

// Outputs: Values are: 10 and 0
echo "Values are: ".$m." and ".$n;

?>

Please note that running the above code will not echo statements about the $y value. This is because the function stops executing after the first return statement. If we uncomment the line where we use list() to assign the variable value, both $m and $n will be NULL because list() only works with arrays, and the function only returns a number.

Using an array to return multiple values

We know that the return statement can return any type of value. So we can also use this to return an array containing all the values ​​we actually want to return. We can rewrite the above example as follows to return multiple values:

<?php

function multiple_returns($a, $b) {
    $x = 2*$a;
    $y = 3*$b;

    return [$x, $y];
}

list($m, $n) = multiple_returns(5, 18);

// Outputs: Values are: 10 and 54
echo "Values are: ".$m." and ".$n;

?>

From a PHP perspective, you still return a single value, but that single value is an array that can contain multiple other values. This is one of the simplest ways to simulate a function returning multiple values ​​in PHP.

In the above example, we only return two values. However, when more values ​​are involved, things can get a little tricky because you have to remember the correct order of the returned values.

Starting with PHP 7.1, you can use list() with associative arrays. This means that the order in which the elements are returned does not affect the assigned value. Here is an example:

<?php

function multiple_returns($a, $b) {
    $x = 2*$a;
    $y = 3*$b;

    return ['m' => $x, 'n' => $y];
}

list('m' => $m, 'n' => $n) = multiple_returns(5, 18);

// Values are: 10 and 54
echo "Values are: ".$m." and ".$n;

list('n' => $n, 'm' => $m) = multiple_returns(5, 18);

// Values are: 10 and 54
echo "Values are: ".$m." and ".$n;

?>

You can see that the variables $m and $n get the same value in both cases because the value is now assigned based on the key instead of the numeric index.

Starting with PHP 7.1, you don't even need to use list() as PHP now supports destructuring syntax. We can rewrite the previous example as:

<?php

function multiple_returns($a, $b) {
    $x = 2*$a;
    $y = 3*$b;

    return ['m' => $x, 'n' => $y];
}

['m' => $m, 'n' => $n] = multiple_returns(5, 18);

// Values are: 10 and 54
echo "Values are: ".$m." and ".$n;

['n' => $n, 'm' => $m] = multiple_returns(5, 18);

// Values are: 10 and 54
echo "Values are: ".$m." and ".$n;

?>

Using an object to return multiple values

Another way to return multiple values ​​from a PHP function is to return an object. We can define classes with different properties using public member variables. One disadvantage of this technique is that you have to write more code, so it will consume more memory to store multiple instances of the class. The advantage is that you can use the same set of variables in multiple places.

<?php

class ValueStore {
    public $m;
    public $n;
}

function multiple_returns_class($a, $b) {

    $my_values = new ValueStore();
    $my_values->m = 2*$a;
    $my_values->n = 3*$b;

    return $my_values;
}

$values = multiple_returns_class(5, 18);

// Values are: 10 and 54
echo "Values are: ".$values->m." and ".$values->n;

?>

As you can see, we can successfully get multiple values ​​from a function simply by creating an object and assigning values ​​to its various properties.

Final Thoughts

In this tutorial, you learned that PHP does not allow you to return multiple values ​​directly from a function. However, you can work around this limitation by packing multiple values ​​into an array or object. After that you just return the array or object from the function and access the values.

The above is the detailed content of How to return multiple values ​​from one PHP function. 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
php函数返回值可以有几个php函数返回值可以有几个Apr 26, 2022 pm 08:14 PM

php函数返回值只能有一个。在PHP中,函数返回值使用return语句定义,语法“return 返回值;”。return语句只能返回一个参数,即函数只能有一个返回值;如果要返回多个值的话,就需在函数中定义一个数组,将返回值存储在数组中返回。

php传参都是字符串吗php传参都是字符串吗Dec 15, 2022 pm 03:07 PM

不是,php传参可以是字符串、数字、布尔值、数组等。从PHP5.6版本开始支持传递数组参数,函数的形式参数可使用“…”来表示函数可接受一个可变数量的参数,而可变参数将会被当作一个数组传递给函数,语法“function 函数名(...$arr){//执行代码}”。

php函数的参数赋值有哪几种php函数的参数赋值有哪几种Apr 24, 2022 pm 12:10 PM

php函数的参数赋值有3种:1、值传递赋值,将实参的值复制一份再赋值给函数的形参;2、引用传递赋值,把实参的内存地址复制一份,然后传递给函数的形参,进而将实参值赋值给形参;3、直接给函数的参数指定默认值,语法“函数名(参数变量='值')”。

PHP函数的命名规范及规则PHP函数的命名规范及规则May 19, 2023 am 08:14 AM

PHP作为一种非常流行的脚本语言,有着强大的函数库支持,其函数的命名规范和规则对于开发效率和代码可读性都有着重要的影响。本文将介绍PHP函数的命名规范及规则。一、命名风格在PHP中,函数名需要严格符合命名规范和规则,规范主要包括两个方面:命名风格和命名规则。1.下划线命名法下划线命名法是PHP函数命名最常用的方式,也是官方推荐的一种方式。遵循这种方式的函数名

详细介绍PHP函数和方法的区别详细介绍PHP函数和方法的区别Mar 24, 2023 am 09:45 AM

随着互联网技术的发展,PHP已经成为了非常流行的开发语言之一。身为一个PHP开发者,了解PHP函数和方法的区别是非常重要的,因为它们在编写代码的时候都是必不可少的。在本文中,我们将详细介绍PHP函数和方法的区别。

PHP函数的迭代器函数PHP函数的迭代器函数May 19, 2023 am 08:11 AM

随着现代编程语言的不断发展,编程的效率和功能性也不断提高,其中PHP作为一种广泛使用的服务器端脚本语言,也在不断地更新和完善其自身的功能列表。PHP函数的迭代器函数就是其中的一种新功能,为PHP程序员提供了更加灵活和高效的编程方式。在本文中,我们将详细介绍PHP函数的迭代器函数的相关知识。什么是PHP函数的迭代器函数?在介绍PHP函数的迭代器函数之前,我们首

php中递归函数是啥意思php中递归函数是啥意思May 31, 2022 pm 12:01 PM

在php中,递归函数指的是自调用函数,也就是函数在函数体内部直接或间接地自己调用自己;使用递归函数时,需要在函数体中附加一个判断条件,以判断是否需要继续执行递归调用,当条件满足时会终止函数的递归调用。

PHP函数的MSSQL函数PHP函数的MSSQL函数May 18, 2023 pm 11:31 PM

PHP是一种开源的服务器端脚本语言,通常用于开发Web应用程序。PHP具有易学易用、灵活、性能优异等优点,因此在Web开发领域得到了广泛应用。而MSSQL作为一种流行的关系型数据库管理系统,也被PHP所支持。在PHP中实现MSSQL数据库操作,需要使用MSSQL函数。MSSQL函数可用于连接数据库、执行查询语句、读写数据库中的数据等操作。接下来,将详细介绍一

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),