0

I prefer to program in Python language, but have to work in PHP for a specific web site app project.

In PHP I am trying to "return" a value from a function to the main program environment (to be used for subsequent calculations), but no matter what I try the value calculated in my function is not returning the value (but echoing from function works fine).

In Python I never had an issue with returning variables: i.e. all values returned from functions were available and accessible to the main program and/or other functions that called the function that produces the return value.

Can someone please tell me how I can solve this issue? I have been searching google and sites ike stackoverflow for the last 2 days with no success. I have many O'Reilly computer books including many on PHP where I have cross referenced my research and read everything I can about the RETURN function - it seems I am doing everything right and even specifically declaring the value to be returned. It is critical that I am able to return values and have access to those values in order to proceed with development on this project - else I am stuck if I cannot return values to be processed further!!

Here is the relevant code pieces:

// DECLARE FUNCTIONS

// FUNCTION
function Calculation_IsArray ($ArrayAny){
    if (is_array($ArrayAny)) {
        echo '<div>THIS VAR IS AN ARRAY</div>';
        $Var_IsArray = TRUE;
        return $Var_IsArray;
    } else {
        echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
    }

}

After declaring the functions and doing some initial calculations to grab an array for checking, I call the above function as follows:

// CALL FUNCTION
Calculation_IsArray($ArrayOfValues);

I am expecting the program to call the function Calculation_IsArray() and pass it the array to be checked ($ArrayOfValues). You can see from the output below that the array is passed and checked and confirmed to be of array type, and both the FOREACH loop as well as the IF/ELSE conditions are working fine and echoing the correct output. However, the above code does not return any values as you can see the NULL values that are echoed when I check for returned values (i.e. that array that was checked) accessible from the main program after the "return".

And here are the results echoed to browser screen (output):


THIS VAR IS AN ARRAY
RETURNED ARRAY =
NULL
VALUE OF $Var_IsArray =
NULL
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 0, VALUE = Array
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 1, VALUE = Array

I have searched here at stackoverflow and found reports of similar problems (and I even tried to test those suggestions for solutions, e.g. placing return at various places in my function to test where it would work), but nothing is working, and this failure to return value is not logical according to what I have read that PHP returns values if expliciting told to RETURN.

Thank you very much for any help in this matter!

[After submission of the original question above]:

I am now trying to isolate my problem by creating a test script called TestReturn.php.

In that script I have placed the following code, but still there is no value returned!!

// DECLARE FUNCTIONS

        // FUNCTION
        function Calculation_IsArray ($ArrayAny){
            if (is_array($ArrayAny)) {
                echo '<div>THIS VAR IS AN ARRAY</div>';
                $Var_IsArray = TRUE;
                return $Var_IsArray;
            } else {
                echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
            }   
        }

        // BEGIN MAIN PROGRAM
        $x = array(1, 2, 3, 4, 5, 6, 7);
        Calculation_IsArray($x);

        // COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
        echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $Var_IsArray . '</div>';
        var_dump($Var_IsArray);

And here is the output in HTML to browser tab/window/terminal:


THIS VAR IS AN ARRAY
HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:
NULL

"Captain, this does not compute!", i.e. this doesn't make sense to me why PHP is not returning my value that I specifically tell it to return to main program!

I have tried all possibilities of coding including:

 return $variable;
 return ($variable);
 return() ;  // i.e. I read somewhere that PHP by default returns the last calculated value in a function.
 return ;

Why is PHP not returning my value/variable back to main program?

4
  • Why don't you return false in the else block? Commented Jul 24, 2016 at 5:42
  • 1
    It would help if you could post the code which actually tries to use the returned value. Commented Jul 24, 2016 at 5:43
  • Thanks, friends! After I posted original post, I went back and did some tests and updated the post here with simplified code which actually tries to use the returned value here for you guys to copy and paste complete isolated code of the problem. I have tried using the return false, but by default PHP (I read) returns false/NULL. Commented Jul 24, 2016 at 6:10
  • How do you dumping $Var_IsArray outside it's function scope? Commented Jul 24, 2016 at 6:27

5 Answers 5

5

When you return something from a function, it doesn't make the variable itself available in the calling scope (i.e. outside the function). In other words, $Var_IsArray only exists inside the function.

Only the contents of the variable are returned, and you must use the result immediately where you call the function; e.g. store it for future reference, pass it to another function, or test it in a condition.

For example:

function foo()
{
    $vals = ['red', 'green', 'blue'];
    return $vals;
}

$somedata = foo();

In this example, $somedata will end up holding the array that previously was stored in $vals.

This is the standard behaviour for return statements (or equivalent functionality) in most programming languages. There are other ways to get variables out of a function, e.g. by using global variables. Generally, they're not good practice though.

I've used Python before too, and I don't think it's any different (unless I've missed a major language feature). You might want to double-check that your Python code is doing what you think it's doing, otherwise you could end up with some nasty bugs in future.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I think I just figured it out myself (and tested it a few times - it is now returning variables, thank GOD!!) while you were writing this, and remembered that this is what I do in Python: I made a variable equal to the function call! Yes, you are right brother! This is the solution! I will post my answer in editing of original post so that you guys can see the code solution - thank GOD our Creator who is Gracer of Knowledge! Honen HaDa'at!!
0

you could simplify the function to the following so it always returns something ( true,false )

function Calculation_IsArray( $ArrayAny ){
    echo is_array($ArrayAny) ? '<div>THIS VAR IS AN ARRAY</div>' : '<div>THIS VAR IS **NOT** AN ARRAY</div>';
    return is_array($ArrayAny);
}

1 Comment

I don't need to return if it is an array. I check if it is an array and if it is, then I need to calculate some values and return them as array back to main program for further calculations in other functions each with specific purpose.
0

Hope this will help:

// FUNCTION
function Calculation_IsArray ($ArrayAny){
    if (is_array($ArrayAny)) {
      echo '<div>THIS VAR IS AN ARRAY</div>';           
      return true;
    } else {
      echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
      return false;
    }
}

$array = array(1, 1, 1);
if ( Calculation_IsArray($array) ){
    print_r( $array );
}    

1 Comment

No, it does not solve the issue since already my program successfully echoes back HTML. I need it to return the calculated values/variables and to be able to have access to these from the main program (which executes all the functions of the program each in sequence and called only as needed to simply my code).
-1
<?php 
// DECLARE FUNCTIONS

// FUNCTION
function Calculation_IsArray ($ArrayAny){
    if (is_array($ArrayAny)) {
        echo '<div>THIS VAR IS AN ARRAY</div>';
        //$Var_IsArray = TRUE;
        return true;
    } else {
        echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
    }   
}

// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$status = Calculation_IsArray($x);

if($status == true){
    // COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
    echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:<br />' . print_r($x) . '</div>';
    var_dump($x);
}

5 Comments

The issue is that I need to do some additional calculations within this function and return the value to the main program for later processing. It is not enough to just return true that it is an array. I check for if it is of type array and then do some additional calculations. These calculated values need to be returned. I am testing returning with just one variable to be simple. So if I can't return simple single variable, I can't return a more complicated array. Therefore I need solution to this return issue before I can move on. In Python this would not even be an issue...
You can do all stuff with your array in function Calculation_IsArray(); what you wants and can return that stuff in function in place for return true.
Your code for me produced the following syntax error: Parse error: syntax error, unexpected $end in /public_html/testreturn.php on line 91
I don't want to return true. I want to check IF array type, THEN I want to do calculations and then return a new array from those calculations. The problem is that nothing is returning as you can see. Have you tried running my code (simplied self-contained version) above to see what results you get on your computer? Are you also getting NULL returned despite specific RETURN called with specific variable to be returned?
The syntax error in your code probably means that you forgot to close a { } pair with the end } or forgetting to close a statement with semi-colon; ; - at least that is what I have read here at stackflow and seen.
-1

ok, so while Peter Bloomfield was responding and writing his CORRECT answer, I was hacking away myself and trying different things and remembered that what I also do in Python is make a variable equal to the function call!! I tried that and now it is returning fine anything I do with that function, thank GOD!!

Here is the updated code in main program now that received ok the returned value (it is no longer returning just NULL):

// BEGIN MAIN PROGRAM
        $x = array(1, 2, 3, 4, 5, 6, 7);
        $ResultOfCalculation = Calculation_IsArray($x);

        // COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
        echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $ResultOfCalculation . '</div>';
        var_dump($ResultOfCalculation);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.