Malkalypse
Malkalypse

Reputation: 45

Why do I get "Notice: Undefined offset" from arrays passed as arguments?

What am I doing wrong here that is causing me to get this message?

function numbered_array( $array ) {    
    for ( $i = 0; $i < count( $array ); $i++ ) {
        echo $i . ": ";
        echo $array[$i] . "<br/>\n";
    }
}

I only have this problem from inside a function. When I use the same code on its own, e.g.

for ( $i = 0; $i < count( $my_array ); $i++ ) {
    echo $i . ": ";
    echo $my_array[$i] . "<br/>\n";
}

it works just fine.

I seem to be having this issue with ANY function to which arrays are passed as arguments.

(For reference, I am working with a 1 dimensional array of string values)

Upvotes: 0

Views: 32

Answers (1)

John
John

Reputation: 222

Here is a solution for your problem.

function numbered_array(array $array)
{
    foreach ($array as $key => $value) {
        echo $key . ": ";
        echo $value . "<br/>\n";
    }
}

$array = array("test","test","test","test",);

numbered_array($array);

Output

0: test<br/>
1: test<br/>
2: test<br/>
3: test<br/>

Upvotes: 1

Related Questions