Skip to content
Advertisement

How to access multiple variables outside foreach loop in php

I am not a php pro and have already explored different online search forums but could not find any suitable answer and that’s why posting my question here.

Function One: Runs a query to database and define variables in foreach loop as follows:

function myFunction(){
 $dbinfo = get_db_info();
 $users = $dbinfo->get_results("
    SELECT 
       Email,
       ID,
       Name,
       Address
        FROM Database_table
        WHERE ID = 5
    ");
    
    if($users) {
        $output = '';
        foreach($users as $user) {
            $ID = $user->ID;
            $dname = $user->Name;
            $email = $user->Email;
            $address = $user->Address;
        }else{
            $output .= 'No user found';
        }

    }//endif
    return $output;
}

Function two: Now I want to get the values of those variables in another function as follows:

function dislayData(){

    $values = myFunction();
    echo $values=>$email;

}

But it does not work. It seems I may need to wrap variables in the foreach loop into an array. I don’t understand how to do that.

Any help here would be highly appreciated.

Thanks in advance.

Bakar

Advertisement

Answer

function myFunction(){
    $dbinfo = get_db_info();
    $users = $dbinfo->get_results("SELECT Email, ID, Name, Address
                                    FROM Database_table
                                    WHERE ID = 5");
    
    if($users) {
        $arrOutput = [];
        foreach($users as $user) {
            $arrOutput[]    =   [
                'ID'    =>  $user->ID,
                'dname' =>  $user->Name,
                'email' =>  $user->Email,
                'address'   =>  $user->Address
            ];
        }
        return $arrOutput;
    }
    else{
        return false;
    }
}

function dislayData(){

    $values = myFunction();

    if($values !== false){
        foreach($values as $user){
            // Now you can access property of each uesr
            echo $user['email'];
        }
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement