lemonpole
lemonpole

Reputation: 127

PHP Array Not Working in Function

I'm currently experimenting with arrays in PHP, and I created a fake environment where a team's information will be displayed.

    $t1 = array (
            "basicInfo" => array (
                "The Sineps",
                "December 25, 2010",
                "lemonpole"
            ),
            "overallRecord" => array (0, 0, 0, 0),
            "overallSeasons" => array (
                1 => array (14, 0, 0),
                2 => array (9, 5, 2),
                3 => array (12, 4, 0),
                4 => array (3, 11, 2)
            ),
            "games" => array (
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />"
            ),
            "seasonHistory" => array (
                "Season I",
                "Season II",
                "Season III",
                "Season IV"
            ),
            "divisions" => array (
                "Open",
                "Main",
                "Main",
                "Invite"
            )
        );
// Displays the seasons the team has been in along
    // with the record of each season.
    function seasonHistory() {
        // Make array variable local-scope.
        global $t1;

        // Count the number of seasons.
        $numrows = count($t1["seasonHistory"]);

        // Loop through all the variables until
        // it reaches the last entry made and display
        // each item seperately.
        for($v = 0; $v <= $numrows; $v++) {
            // Echo each season.
            echo "<tr><td>{$t1["games"][$v]}</td>";
            echo "<td>{$t1["seasonHistory"][$v]}</td>";
            echo "<td>{$t1["divisions"][$v]}</td></tr>";
        }
    }

I have tested several possible problems out and after narrowing them down I have come down to one conclusion and that is my function is not connecting to the array for some reason. I don't know what else to do because I thought making the array global would fix that problem.

What works:

  1. I can echo $t1["games"][0] on the page I need it to display and it gives me the content.

  2. I tried echo $t1["games"][0] INSIDE the function and then calling the function and it doesn't display anything.

Upvotes: 0

Views: 4365

Answers (2)

German Rumm
German Rumm

Reputation: 5822

This can happen if you define your $t1 not in the global scope. Try explicitly putting it into globals, by doing $GLOBALS['t1'] = $t1; right after you define your variable.

Upvotes: 3

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

extract($t1);

Try this function instead of global.

Better idea is to pass array as argument...

function seasonHistory($array){

$t1 = $array;

//your function
}

Upvotes: 2

Related Questions