How to pass an array into a function, and return the results with an array

后端 未结 9 1406
你的背包
你的背包 2021-02-05 07:25

So I\'m trying to learn how to pass arrays through a function, so that I can get around PHP\'s inability to return multiple values. Haven\'t been able to get anything to work so

相关标签:
9条回答
  • 2021-02-05 07:55
    function foo(Array $array)
    {
         return $array;
    }
    
    0 讨论(0)
  • 2021-02-05 07:56

    You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

    function foo(&$arr) { # note the &
      $arr[3] = $arr[0]+$arr[1]+$arr[2];
    }
    $waffles = array(1,2,3);
    foo($waffles);
    echo $waffles[3]; # prints 6
    

    That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

    0 讨论(0)
  • 2021-02-05 07:58

    Another way is:

    $NAME = "John";
    $EMAIL = "John@gmail.com";
    $USERNAME = "John123";
    $PASSWORD = "1234";
    $array = Array ("$NAME","$EMAIL","$USERNAME","$PASSWORD");
    function getAndReturn (Array $array){
        return $array;
    }
    print_r(getAndReturn($array));
    
    0 讨论(0)
  • 2021-02-05 08:04

    I always return multiple values by using a combination of list() and array()s:

    function DecideStuffToReturn() {
        $IsValid = true;
        $AnswerToLife = 42;
    
        // Build the return array.
        return array($IsValid, $AnswerToLife);
    }
    
    // Part out the return array in to multiple variables.
    list($IsValid, $AnswerToLife) = DecideStuffToReturn();
    

    You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.

    See list() for more information.

    0 讨论(0)
  • 2021-02-05 08:07

    Try

    $waffles = foo($waffles);
    

    Or pass the array by reference, like suggested in the other answers.

    In addition, you can add new elements to an array without writing the index, e.g.

    $waffles = array(1,2,3); // filling on initialization
    

    or

    $waffles = array();
    $waffles[] = 1;
    $waffles[] = 2;
    $waffles[] = 3;
    

    On a sidenote, if you want to sum all values in an array, use array_sum()

    0 讨论(0)
  • 2021-02-05 08:08

    You are not able to return 'multiple values' in PHP. You can return a single value, which might be an array.

    function foo($test1, $test2, $test3)
    {
        return array($test1, $test2, $test3);
    }
    $test1 = "1";
    $test2 = "2";
    $test3 = "3";
    
    $arr = foo($test1, $test2, $test3);
    
    $test1 = $arr[0];
    $test2 = $arr[1];
    $test3 = $arr[2];
    
    0 讨论(0)
提交回复
热议问题