Forum Moderators: coopster

Message Too Old, No Replies

foreach...strange behavior

foreach returning array rather then a string

         

zeeshan12

10:21 am on Apr 26, 2005 (gmt 0)

10+ Year Member



Hi,

I'm facing this strange problem with foreach. I have built a site on my local system (Win XP, Apache2, PHP 4.3.10) and "foreach" loop works fine.

e.g

$a = array("1-2","2-4","4-2");
foreach ($a as $v)
echo $v;

this runs fine on my local system and prints

1-22-44-2

but when i run this same script on the remote server (Linux, Apache2, PHP 4.3.10) it prints

ArrayArrayArray

did anyone else here ever had this problem....?..please help!

zeeshan.

TheCoupe

10:43 am on Apr 26, 2005 (gmt 0)

10+ Year Member



Hi, I'm fairly new to this, but you could try:

$a = array("1-2","2-4","4-2");
n = count($a);
for ($i = 0; $i <= $n; $i++)
{
echo ($a[$i]);
echo '<br>';
}

zeeshan12

10:53 am on Apr 26, 2005 (gmt 0)

10+ Year Member



Hi,

I have tried using this

foreach($a as $key=>$v)
echo $v;

and it works fine but that means i'll have to change all my php files and put this new "foeeach" code in them and its gonna take a long time since i'ev got alot of files n i'ev used foreach in almost all of them..

I'm wondering why isnt it working fine on the remote server when the versions on Apache and PHP are the same as my local server.

TheCoupe

11:06 am on Apr 26, 2005 (gmt 0)

10+ Year Member



not sure if this is correct, but could it be that the PHP on the Linux server is compiled differently?

Try what I've suggested and see if it works anyway

zeeshan12

11:42 am on Apr 26, 2005 (gmt 0)

10+ Year Member



i'm sure wot u'ev sent will work fine since this code works fine on linux server

foreach($a as $key=>$v)
echo $v

but if i change it back to

foreach($a as $v)
echo $v

it starts printing "Array" as the value of $v.

brucec

2:48 pm on Apr 26, 2005 (gmt 0)

10+ Year Member



zeeshan, some servers require the curly braces when you use foreach.

Try using the { and } and it may work :)

zeeshan12

3:23 pm on Apr 26, 2005 (gmt 0)

10+ Year Member



i am using curly braces in my actual code...i wrote this code there jus to explain my problem in simple words.

if its becuase of curly braces then it shouldnt work when i give that optional "$key" variable in loop condition

coopster

3:11 am on Apr 27, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I recalled something about a foreach patch once ... does this shed any light?

[webmasterworld.com...]