2

I have an array called $worker
the array consists of only strings, each of which has multiple lines.

if I do

var_dump($worker); 

it displays all the information, but do

for($i=0,$size=sizeof($worker);$i<$size;++$i)
{
    echo $worker[i];
}

I end up with nothing on the page.

I'm very new to php, so sorry if this is a noob question: how do I get the information in the array to print to the screen correctly?

motsu35
  • 21
  • 2
  • 5

3 Answers3

5

You're missing the '$' for your '$i' variable inside the for loop.

It's a good idea to turn on error reporting while developing in PHP: http://php.net/manual/en/function.error-reporting.php

This is the conventional syntax for for loops in PHP:

for ($i=0, $c=count($worker); $i<$c; $i++) {
    echo $worker[$i];
}
Jordon Bedwell
  • 3,189
  • 3
  • 23
  • 32
asdf
  • 176
  • 5
  • 1
    A little more detail on what is actually going wrong with the missing $. When PHP sees `$worker[i]` it thinks that `i` is a bare string instead of a variable. Since there is no constant named `i` it converts `i` into a string and tries to access `$worker['i']` since PHP arrays work like associative arrays. Since `$worker['i']` hasn't been set it returns `null`. `echo null` prints an empty string. Also, as the code @asdf posted points out in PHP it is customary to use `count` instead of `sizeof`, `sizeof` is just an alias of `count`. – Useless Code Jun 05 '11 at 20:34
3
for($i=0,$size=count($worker);$i<$size;++$i)
{
echo $worker[$i];
}

You forgot '$' int echo $worker[$i];

Jordon Bedwell
  • 3,189
  • 3
  • 23
  • 32
therealszaka
  • 453
  • 4
  • 20
1

You forgot the dollar sign before i in $worker[$i].

-edit-: Removed the second part, maybe I'm too tired :)

patapizza
  • 2,398
  • 15
  • 14