Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php foreach echo prints "Array" as value

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

like image 793
Edge D-Vort Avatar asked Nov 21 '12 01:11

Edge D-Vort


3 Answers

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
}
?>
like image 183
Lior Avatar answered Nov 05 '22 02:11

Lior


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";
}
?>
like image 44
Twisty Avatar answered Nov 05 '22 03:11

Twisty


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'); 
like image 33
Frank Avatar answered Nov 05 '22 04:11

Frank