Philll_t
Philll_t

Reputation: 4437

PHP Array issue when looping and echoing

I'm having trouble getting the array to work right, let me show you the code here

function scanArray(){
$al = sizeof($_userLoaders);
echo $al. "<br />";
for ($tr = 0; $tr <= $al; $tr++) {
echo  "value: " .$tr. "<br />";
echo $_userLoaders[$tr];


}



}

//Fetch user's loaders.

$_userLoaders;

function get_user_loaders(){ 

         $con = connectToMySQL();//connects to my_sql

        mysql_select_db("my_database", $con);//connect database

        $t = mysql_query("SELECT * FROM someTable
        WHERE value_a=".$_SESSION['value_a']." AND value_b=someValue");
        $x= 0;
        //lets loop through the results and create an array to compare later.
            while ($result = mysql_fetch_array($t)){
             $_userLoaders[$x] = $result['value_c'];
                $x++;
            }
        //lets get all the options for
        print_r($_userLoaders);//this part prints what it should
scanArray();
}

okay, I minimized the code above to show you what's going on. Pretty much function get_user_loaders() works great. It fetches data from a table in a database, and returns what it should. Second, it makes an array out of it. Again, this part works great. When the print_r() method is called it prints what it should, here's an example of what it prints:

Array ( [0] => tableValue )

yes, at this point it only has one value, please note that this value can vary from no values to 100 values which is why I am using an array. In this case, i'm testing it with one value.

Now, once I call scanArray() It doesn't echo the values.

the scanArray() function echoes the following:

0
value: 

so what I don't understand is why does it print it out, but it doesn't display the function? Thanks in advance.

Upvotes: 0

Views: 102

Answers (2)

Ynhockey
Ynhockey

Reputation: 3932

That would be because $_userLoaders is not equal to anything inside your scanArray() function. While it's not good practice, you can add the line:

global $_userLoaders;

to your scanArray() function and every other function that uses that global variable then, and it should work.

Upvotes: 1

Aleks G
Aleks G

Reputation: 57316

Your problem is that $_userLoaders variable is declared outside the function and function scanArray knows nothing about it. You need to either pass that variable in as a parameter:

function scanArray($_userLoaders) {
    ...
}

with the call at the end being

scanArray($_userLoaders);

or alternatively declare the variable as global inside the function:

function scanArray($_userLoaders) {
    global $_userLoaders;
    ...
}

Upvotes: 2

Related Questions