Perhaps I'm simply having trouble understanding how php handles arrays.
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
<?php 
    $someArray[]=array('1','2','3','4','5','6','7'); // size 7
    foreach($someArray as $value){ 
        echo $value;    
?> 
<br />
<?php
    }
?>
This prints out this:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
This works:
<?php 
    $someArray[0] = '1';
    $someArray[1] = '2';
    $someArray[2] = '3';
    $someArray[3] = '4';
    $someArray[4] = '5';
    $someArray[5] = '6';
    $someArray[6] = '7';
    for($i=0; $i<7; $i++){
        echo $someArray[$i]."<br />";
    }
?>
Why won't the foreach work?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
You haven't declared the array properly.
You have to remove the square brackets: [].
<?php 
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){ 
    echo $value;    
?>  <br />
<?php
}
?>
                        Try:
<?php 
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){ 
    echo $value . "<br />\n";
}
?>
Or:
<?php
$someArray = array(
  0 => '1',
  'a' => '2',
  2 => '3'
);
foreach($someArray as $key => $val){
  echo "Key: $key, Value: $val<br/>\n";
}
?>
                        actually, you're adding an array into another array.
$someArray[]=array('1','2','3','4','5','6','7'); 
the right way would be
$someArray=array('1','2','3','4','5','6','7'); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With