Sven
Sven

Reputation: 13275

Returning array inside function that returns another value

Why does the following script does not work?

$arr = array();

function collect( $array , $val) {
    $array[] = $val;
    return $array;
}

function checkFoo( $s ) {

    $valid = true;

    if ( strlen( $s ) === 0 ) {
        $isValid = false;
        collectFoo( $arr , $s );
    }

    return $valid;
}

function checkBar( $t ) {

    $valid = true;

    if ( strlen( $s ) != 10 ) {
        $isValid = false;
        collectFoo( $arr , $t );
    }

    return $valid;
}

if ( checkFoo( $that ) && checkBar( $this ) ) {

    echo "success"; 

} else {

    print_r( $error );

}

I always get

Notice: Undefined variable: error in /my.php on line 12

where line 12 resembles the second occurrence of collect(...);

I know that a function can only return one value, but what if a function returns something in a function that returns something? Because collect returns $array inside checkBar that returns $valid.

Upvotes: 1

Views: 119

Answers (3)

DJafari
DJafari

Reputation: 13545

Edited

You need more practice, because totally your code is incorrect ! you must changes this parts of your codes :

$arr = array();

function collectFoo( $arr , $val) {
    global $arr;

    $arr[] = $val;
}

function checkFoo( $s ) {
    global $arr;

    $valid = false;
    if ( strlen( $s ) === 0 ) {
        $valid = false;
        collectFoo( $arr , $s );
    }
    return $valid;
}

function checkBar( $t ) {
    global $arr;

    $valid = true;
    if ( strlen( $t ) != 10 ) {
        $valid = false;
        collectFoo( $arr , $t );
    }
    return $valid;
}

$a = checkFoo( $that );
$b = checkBar( $this );
if ( $a && $b ) {
    echo 'Success !';
} else {
    print_r( $err );
}

Upvotes: 0

SuperTron
SuperTron

Reputation: 4233

You aren't declaring your $arr variable as global inside the functions that use it. You can find some info about that here.

Also, it doesn't look like you are actually using the return value of collect, so I'd say that your problem is that either checkBar or checkFoo are returning false, which makes you fall through to the print_r function, with a $error variable that you have not initialized.

Finally, it seems to me like your collect function is not actually doing anything to the $arr variable, because you are not passing it to collect by reference. you can read up on passing variables by reference here. There is also a S.O. question about this here.

Upvotes: 0

Alon Eitan
Alon Eitan

Reputation: 12025

you are using a global variable ($arr), so you need do declare it as such. example:

function checkFoo( $s ) {
    global $arr; // declare $arr to be usable inside this function scope
    $valid = true;

    if ( strlen( $s ) === 0 ) {
        $isValid = false;
        collectFoo( $arr , $s );
    }

    return $valid;
}

Upvotes: 1

Related Questions