Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print array with for loop

I want to print this array to all indexes upto 21, but in this code this is printing only to array length, what i should i do the print whole array in for loop?

<?php
$array=array(0=>"hello",
             1=>"world", 
             2=>"this", 
             3=>"is", 
             4=>"an", 
             20=>"array",
             21=>"code" );

$length=count($array);

for($i=0;$i<$length;$i++){
         echo "$i=>".$array[$i]; 
         echo "<br />";

      }
?>
like image 714
zniz Avatar asked Apr 24 '26 20:04

zniz


2 Answers

Your difficulty is the way you're defining your array:

$array=array(0=>"hello",
             1=>"world", 
             2=>"this", 
             3=>"is", 
             4=>"an", 
             20=>"array",
             21=>"code" );

Arrays in php are really hashmaps; when you call index 5 on the above array, it is undefined. No index item up to 20 will be defined, and these will Notice out:

PHP Notice:  Undefined offset:  5

Because you're using array length as your iterating variable, and calling exactly that variable, you will never get positions 20 and 21 in your code.

This is what your array looks like to the computer:

0 => "hello"
1 => "world"
2 => "this"
3 => "is"
4 => "an"
5 => NULL
6 => NULL
7 => NULL
... //elided for succinctness 
19 => NULL
20 => "array"
21 => "code"

When you call $array[7] it can't return anything. When you call $array[20] it will return "array".

What you really want is a foreach loop:

foreach($array as $key => $val) {
    //key will be one of { 0..4, 20..21}
    echo "$key is $value\n";
}

Resulting in:

$ php test.php 
0 is hello
1 is world
2 is this
3 is is
4 is an
20 is array
21 is code

If you must use a for loop:

$key_array = array_keys($array);
for($i=0;$i<count($key_array);$i++){
   $key = $key_array[$i];
   echo "$key => ".$array[$key]."\n";
}

Note this is not a clean solution.

like image 127
Nathaniel Ford Avatar answered Apr 26 '26 11:04

Nathaniel Ford


Solution with a for loop:

$array=array(0=>"hello",
             1=>"world", 
             2=>"this", 
             3=>"is", 
             4=>"an", 
             20=>"array",
             21=>"code" );

$max = max(array_flip($array)); // What if max array key is 10^5 ?
for($i=0;$i<=$max;$i++){
    if(isset($array[$i])){
        echo "$i=>".$array[$i]."<br>";
    }
}
like image 44
HamZa Avatar answered Apr 26 '26 09:04

HamZa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!