6

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

3 Answers 3

16

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
}
?>
Sign up to request clarification or add additional context in comments.

2 Comments

+1. To be completely clear to the OP, the []= operator means, essentially, "append the right-hand argument to the array which is the left-hand argument." Thus, you've appended the array ['1','2','3','4','5','6','7'] to nothingness, resulting in [['1','2','3','4','5','6','7']]; an array whose first (and only) element is the array you've specified.
That's exactly what it was. Man... I'm a victim of cross-language syntax confusion. I'm too used to java :)
6

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";
}
?>

Comments

2

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'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.