[PHP] Re: Foreach and mydql_query problem

2013-07-22 Thread Tim Streater
On 22 Jul 2013 at 12:56, Karl-Arne Gjersøyen karlar...@gmail.com wrote: 

 Yes, i know that only one a singe row is updated and that is the problem.
 What can I do to update several rows at the same time?

Which several rows? The row that will be updated is that (or those) that match 
your WHERE clause. Seems to me you should make sure your WHERE is correct.

--
Cheers  --  Tim

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

[PHP] Re: Foreach and mydql_query problem

2013-07-22 Thread Karl-Arne Gjersøyen
2013/7/22 Tim Streater t...@clothears.org.uk

 On 22 Jul 2013 at 12:56, Karl-Arne Gjersøyen karlar...@gmail.com wrote:

  Yes, i know that only one a singe row is updated and that is the problem.
  What can I do to update several rows at the same time?

 Which several rows? The row that will be updated is that (or those) that
 match your WHERE clause. Seems to me you should make sure your WHERE is
 correct.


Thanks, Tim.
Yes the form is generated in a while loop and have input type=number
name=number_of_items[] size=6 value=?php echo $item; ?. This
field is in several product rows and when I update the form the foreach
loop write all (5) products correct. But the other way: Update actual rows
in the  database did not work. Only the latest row is updated..

Karl


Re: [PHP] Mystery foreach error

2013-03-13 Thread Jim Giner

On 3/12/2013 9:04 PM, Angela Barone wrote:

On Mar 12, 2013, at 5:16 PM, David Robley wrote:

Presumably there is a fixed list of State - those are US states? -



so why not provide a drop down list of the possible choices?


There is, but the problem must have been that if someone didn't select a State, 
$state was blank.  I've since given the Select a State... choice a value of 
'XX' and I'm now looking for that in the if statement I mentioned before.

Angela

Why not just check if the $state exists as a key of the array $states 
before doing this?


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-13 Thread Matijn Woudt
On Wed, Mar 13, 2013 at 5:07 PM, Jim Giner jim.gi...@albanyhandball.comwrote:

 On 3/12/2013 9:04 PM, Angela Barone wrote:

 On Mar 12, 2013, at 5:16 PM, David Robley wrote:

 Presumably there is a fixed list of State - those are US states? -


  so why not provide a drop down list of the possible choices?


 There is, but the problem must have been that if someone didn't
 select a State, $state was blank.  I've since given the Select a State...
 choice a value of 'XX' and I'm now looking for that in the if statement I
 mentioned before.

 Angela

  Why not just check if the $state exists as a key of the array $states
 before doing this?


Exactly, that's much better. It could be that some hacker enters something
other than XX or one of the states..


Re: [PHP] Mystery foreach error

2013-03-13 Thread Angela Barone
On Mar 13, 2013, at 9:07 AM, Jim Giner wrote:
 Why not just check if the $state exists as a key of the array $states before 
 doing this?

Jim,

Are you thinking about the in_array function?

Angela

Re: [PHP] Mystery foreach error

2013-03-13 Thread Matijn Woudt
On Thu, Mar 14, 2013 at 12:18 AM, Angela Barone ang...@italian-getaways.com
 wrote:

 On Mar 13, 2013, at 9:07 AM, Jim Giner wrote:
  Why not just check if the $state exists as a key of the array $states
 before doing this?

 Jim,

 Are you thinking about the in_array function?

 Angela


That wouldn't work, in_array checks the values, and your states are in the
keys. Use:
if(isset($states[$state]))

- Matijn


Re: [PHP] Mystery foreach error

2013-03-13 Thread Angela Barone
On Mar 13, 2013, at 4:24 PM, Matijn Woudt wrote:
 That wouldn't work, in_array checks the values, and your states are in the 
 keys. Use:
 if(isset($states[$state])) 

Hi Matijn,

Before I received your email, I ran across if(array_key_exists) and it 
seems to work.  How does that differ from if(isset($states[$state]))?

Angela
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-13 Thread David Harkness
On Wed, Mar 13, 2013 at 4:44 PM, Angela Barone
ang...@italian-getaways.comwrote:

 I ran across if(array_key_exists) and it seems to work.  How does that
 differ from if(isset($states[$state]))?


Hi Angela,

isset() will return false for an array key 'foo' mapped to a null value
whereas array_key_exists() will return true. The latter asks Is this key
in the array? whereas isset() adds and is its value not null? While
isset() is every-so-slightly faster, this should not be a concern. Use
whichever makes sense for the context here. Since you don't stick null
values into the array, I prefer the isset() form because the syntax reads
better to me.

Peace,
David


Re: [PHP] Mystery foreach error

2013-03-13 Thread Sebastian Krebs
2013/3/14 David Harkness davi...@highgearmedia.com

 On Wed, Mar 13, 2013 at 4:44 PM, Angela Barone
 ang...@italian-getaways.comwrote:

  I ran across if(array_key_exists) and it seems to work.  How does that
  differ from if(isset($states[$state]))?


 Hi Angela,

 isset() will return false for an array key 'foo' mapped to a null value
 whereas array_key_exists() will return true. The latter asks Is this key
 in the array? whereas isset() adds and is its value not null? While
 isset() is every-so-slightly faster, this should not be a concern. Use
 whichever makes sense for the context here. Since you don't stick null
 values into the array, I prefer the isset() form because the syntax reads
 better to me.


Just a minor addition: Because 'null' is the representation of nothing
array_key_exists() and isset() can be treated as semantically equivalent.

Another approach (in my eyes the cleaner one ;)) is to simply _ensure_ that
the keys I want to use exists. Of course this only works in cases, where
the key is not dynamical, or the dynamic keys are known, which is not the
case here, it seems.

$defaults = array('stateNames' = array(), 'states' = array());
$values = array_merge($defaults, $values);
$values['states'] = array_merge(array_fill_keys($values['stateNames'],
null), $values['states']);
if (!$values[$myState]) {

}



 Peace,
 David




-- 
github.com/KingCrunch


Re: [PHP] Mystery foreach error

2013-03-13 Thread David Harkness
On Wed, Mar 13, 2013 at 5:10 PM, Sebastian Krebs krebs@gmail.comwrote:

 Because 'null' is the representation of nothing array_key_exists() and
 isset() can be treated as semantically equivalent.


As I said, these functions return different results for null values. It
won't matter for Angela since she isn't storing null in the array, though.

Peace,
David


Re: [PHP] Mystery foreach error

2013-03-13 Thread Sebastian Krebs
2013/3/14 David Harkness davi...@highgearmedia.com


 On Wed, Mar 13, 2013 at 5:10 PM, Sebastian Krebs krebs@gmail.comwrote:

 Because 'null' is the representation of nothing array_key_exists() and
 isset() can be treated as semantically equivalent.


 As I said, these functions return different results for null values. It
 won't matter for Angela since she isn't storing null in the array, though.


Thats exactly, what I tried to say :)



 Peace,
 David




-- 
github.com/KingCrunch


Re: [PHP] Mystery foreach error

2013-03-13 Thread Angela Barone
On Mar 13, 2013, at 5:02 PM, David Harkness wrote:
 isset() will return false for an array key 'foo' mapped to a null value 
 whereas array_key_exists() will return true. The latter asks Is this key in 
 the array? whereas isset() adds and is its value not null? While isset() 
 is every-so-slightly faster, this should not be a concern. Use whichever 
 makes sense for the context here.

Hi David,

Thank you for the explanation.  It's nice to know the difference 
between them.  Since they are equivalent for my use, I went with 
array_key_exists, simply because it makes more sense to me in English. ;)

Thanks again to everyone.  I got it to work _and_ there are no more 
errors!!!

Angela
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Mystery foreach error

2013-03-12 Thread Angela Barone
I've been getting the following error for awhile now, but I can't 
figure out why it's happening:

Invalid argument supplied for foreach() in ... sample.php on line 377

Here's that portion of code:

include(states_zipcodes.php);

// Check if Zip Code matches from states_zipcodes
$zip_short = substr($zip, 0, 3);
foreach ($states[$state] as $zip_prefix) {   // -- line 377
if ($zip_prefix == $zip_short) {
break;
} else {
$match = 'no';
}
}

It doesn't happen all the time, so I'm thinking that some spambot is 
populating the HTML form with something the script doesn't like(?).  However, I 
tested that myself by entering text, or by entering just 2 digits, but there 
was no error.  FYI, I do have code in the script that catches faulty input and 
warns people in their browser to go back and re-enter the correct data, so I'm 
at a loss as to why this is happening.

How can I see what's triggering this to happen?  I have the following 
line in my php.ini:

error_reporting = E_ALL  E_STRICT  E_NOTICE  E_DEPRECATED

Thank you,
Angela
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-12 Thread Marco Behnke
Am 12.03.13 20:45, schrieb Angela Barone:
   I've been getting the following error for awhile now, but I can't 
 figure out why it's happening:

 Invalid argument supplied for foreach() in ... sample.php on line 377

   Here's that portion of code:

 include(states_zipcodes.php);

 // Check if Zip Code matches from states_zipcodes
 $zip_short = substr($zip, 0, 3);
 foreach ($states[$state] as $zip_prefix) {   // -- line 377

what is in $states?
Looks like $states[$state] is not an array.

And don't use  reference operator in foreach loop, there can be strange
side effects if you don't act carefully with it.

 if ($zip_prefix == $zip_short) {
 break;
 } else {
 $match = 'no';
 }
 }

   It doesn't happen all the time, so I'm thinking that some spambot is 
 populating the HTML form with something the script doesn't like(?).  However, 
 I tested that myself by entering text, or by entering just 2 digits, but 
 there was no error.  FYI, I do have code in the script that catches faulty 
 input and warns people in their browser to go back and re-enter the correct 
 data, so I'm at a loss as to why this is happening.

   How can I see what's triggering this to happen?  I have the following 
 line in my php.ini:

 error_reporting = E_ALL  E_STRICT  E_NOTICE  E_DEPRECATED

 Thank you,
 Angela


-- 
Marco Behnke
Dipl. Informatiker (FH), SAE Audio Engineer Diploma
Zend Certified Engineer PHP 5.3

Tel.: 0174 / 9722336
e-Mail: ma...@behnke.biz

Softwaretechnik Behnke
Heinrich-Heine-Str. 7D
21218 Seevetal

http://www.behnke.biz




signature.asc
Description: OpenPGP digital signature


Re: [PHP] Mystery foreach error

2013-03-12 Thread Angela Barone
On Mar 12, 2013, at 2:26 PM, Marco Behnke wrote:

 what is in $states?
 Looks like $states[$state] is not an array.

Here's a sample:

?php
$states = array(
'AL' = array( '350','351','352','353', ),
'AK' = array( '995','996','997','998','999', ),
'AZ' = array( '850','851','852','853','854', ),
...
'WI' = array( '530','531','532', ), 
'WY' = array( '820','821','822','823','824', ),
);
?


 side effects if you don't act carefully with it.

I don't remember where that came from, but for the most part, this 
script works perfectly.  However, I removed it and will test without it.

Angela
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-12 Thread Jim Giner

$states = array(
'AL' = array( '350','351','352','353', ),
'AK' = array( '995','996','997','998','999', ),
'AZ' = array( '850','851','852','853','854', ),
...
'WI' = array( '530','531','532', ),
'WY' = array( '820','821','822','823','824', ),
);
?
Seeing your structure now, I think the problem is that '$state' is not 
set to a value in the array.  Are you picking a State and assigning it 
to $state before executing this loop?  If not, then $states[$state] is 
undefined which is not an array var.



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-12 Thread Angela Barone
I think I figured it out.

?php
$states = array(
'AL' = array( '350','351','352','353', ),
'AK' = array( '995','996','997','998','999', ),
'AZ' = array( '850','851','852','853','854', ),
'WI' = array( '530','531','532', ), 
'WY' = array( '820','821','822','823','824', ),
);

$zip = 35261;
$state = 'XX';

$zip_short = substr($zip, 0, 3);
foreach ($states[$state] as $zip_prefix) { 
if ($zip_prefix == $zip_short) {
echo State = $state;
} else {
echo 'no';
}
}
?

Running this script, I got the same error as before.  If $state is a 
known state abbreviation in the array, everything is fine, but if someone was 
to enter, say 'XX' like I did above or leave it blank, then the error is 
produced.  I placed an if statement around the foreach loop to test for that 
and I'll keep an eye on it.

Thank you for getting me to look at the array again, which led me to 
look at the State.

Angela

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-12 Thread David Robley
Angela Barone wrote:

 I think I figured it out.
 
 ?php
 $states = array(
 'AL' = array( '350','351','352','353', ),
 'AK' = array( '995','996','997','998','999', ),
 'AZ' = array( '850','851','852','853','854', ),
 'WI' = array( '530','531','532', ),
 'WY' = array( '820','821','822','823','824', ),
 );
 
 $zip = 35261;
 $state = 'XX';
 
 $zip_short = substr($zip, 0, 3);
 foreach ($states[$state] as $zip_prefix) {
 if ($zip_prefix == $zip_short) {
 echo State = $state;
 } else {
 echo 'no';
 }
 }
 ?
 
 Running this script, I got the same error as before.  If $state is a known
 state abbreviation in the array, everything is fine, but if someone was to
 enter, say 'XX' like I did above or leave it blank, then the error is
 produced.  I placed an if statement around the foreach loop to test for
 that and I'll keep an eye on it.
 
 Thank you for getting me to look at the array again, which led me to look
 at the State.
 
 Angela

Presumably there is a fixed list of State - those are US states? - so why 
not provide a drop down list of the possible choices?

-- 
Cheers
David Robley

I need to be careful not to add too much water, Tom said with great 
concentration.


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Mystery foreach error

2013-03-12 Thread Angela Barone
On Mar 12, 2013, at 5:16 PM, David Robley wrote:
 Presumably there is a fixed list of State - those are US states? -

 so why not provide a drop down list of the possible choices?

There is, but the problem must have been that if someone didn't select 
a State, $state was blank.  I've since given the Select a State... choice a 
value of 'XX' and I'm now looking for that in the if statement I mentioned 
before.

Angela

[PHP] Re: foreach

2012-04-05 Thread Jim Giner
I don't know about others, but I can't make sense of this - way too much 
presented with no idea of what I am looking at - code or output.

One thing:  $_Request is not the same var as $_REQUEST. 



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach

2012-04-05 Thread Al



On 4/5/2012 4:15 PM, Ethan Rosenberg wrote:

Dear Lists -

I know I am missing something fundamental - but I have no idea where to start to
look.

Here are code snippets:

I have truncated the allowed_fields to make it easier to debug.

$allowed_fields = array( 'Site' ='POST[Site]', 'MedRec' = '$_POST[MedRec]',
'Fname' = '$_POST[Fname]' );
echo post #1\n;
print_r($_POST);

RESPONSE:

post #1
Array
(
[Site] = AA
[MedRec] = 10002
[Fname] =
[Lname] =
[Phone] =
[Height] =
[welcome_already_seen] = already_seen
[next_step] = step10
)



// $allowed_fields = array(Site, MedRec, Fname, Lname, // previous
statement of $allowed_fields
// Phone, Sex, Height);



Key Site, Value POST[Site]
Key MedRec, Value $_POST[MedRec]
Key Fname, Value $_POST[Fname]



foreach ($allowed_fields as $key = $val) {
print Key $key, Value $val\n;
}


if(isset($_Request['Sex']) trim($_POST['Sex']) != '' )
{
if ($_REQUEST['Sex'] === 0)
{
$sex = 'Male';
}
else
{
$sex = 'Female';
}
}
}
echo Post#2;
print_r($_POST);
if(empty($allowed_fields))
//RESPONSE

Post#2Array
(
[Site] = AA
[MedRec] = 10002
[Fname] =
[Lname] =
[Phone] =
[Height] =
[welcome_already_seen] = already_seen
[next_step] = step10
)



{
echo ouch;
}

foreach ( $allowed_fields as $key = $val ) //This is line 198
{
if ( ! empty( $_POST['val'] ) )
{
print Key $key, Value $val\n;
$cxn = mysqli_connect($host,$user,$password,$db);
$value = mysql_real_escape_string( $_POST[$fld] );
$query .=  AND $fld = '$_POST[value]' ;
echo #1 $query; //never echos the query
}
}

These are the messages I receive on execution of the script:

Notice: Undefined variable: allowed_fields in /var/www/srchrhsptl5.php on line 
198
Warning: Invalid argument supplied for foreach() in /var/www/srchrhsptl5.php on
line 198

Advice and help, please.

Thank you.

Ethan Rosenberg



Break down you code into workable segments and test each one individually. If 
you have a problem with a small segment, ask for help about it specifically.


Folks don't have time to digest and critique your whole code.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-09 Thread David Harkness
On Sat, Jan 7, 2012 at 5:01 PM, Tim Behrendsen t...@behrendsen.com wrote:

 The first loop is leaving a reference to the final element. But then the
 second foreach is doing a straight assignment to the $row variable, but
 $row is a reference to the final element. So the foreach is assigning its
 iterated value to the final element of the array, instead of a normal
 variable.


Exactly, and the fact that it shows 1, 2, 2 in the second loop adds more
confusion, but it makes sense. In the second loop, it assigns the indexed
row value into the third row and displays it. Thus it displays row 1, row
2, and then ... row 3, but row 3 is the one that keeps getting overwritten.
And in the third iteration, it overwrites the third row with the third row
which currently holds what was in row 2.

The moral is always unset the iterator variable when doing foreach with a
 reference, like the manual says. :)


While you can certainly follow the above advice, in my view it's dangerous
to have these two loops a) reuse the same variable name for a different
purpose and b) exist in the same scope. More and more I find myself
dropping the subtle tricks I've learned over the years in favor of writing
code that is as easy to understand as possible. Code gets read and modified
a lot more than it gets written, and all those tricks just trip up more
junior teammates--and often even myself. :)

David


Re: [PHP] Strange foreach reference issue

2012-01-09 Thread Tim Behrendsen

On 1/9/2012 10:35 AM, David Harkness wrote:
On Sat, Jan 7, 2012 at 5:01 PM, Tim Behrendsen t...@behrendsen.com 
mailto:t...@behrendsen.com wrote:


The first loop is leaving a reference to the final element. But
then the second foreach is doing a straight assignment to the $row
variable, but $row is a reference to the final element. So the
foreach is assigning its iterated value to the final element of
the array, instead of a normal variable.


Exactly, and the fact that it shows 1, 2, 2 in the second loop adds 
more confusion, but it makes sense. In the second loop, it assigns the 
indexed row value into the third row and displays it. Thus it displays 
row 1, row 2, and then ... row 3, but row 3 is the one that keeps 
getting overwritten. And in the third iteration, it overwrites the 
third row with the third row which currently holds what was in row 2.


The moral is always unset the iterator variable when doing foreach
with a reference, like the manual says. :)


While you can certainly follow the above advice, in my view it's 
dangerous to have these two loops a) reuse the same variable name for 
a different purpose and b) exist in the same scope. More and more I 
find myself dropping the subtle tricks I've learned over the years in 
favor of writing code that is as easy to understand as possible. Code 
gets read and modified a lot more than it gets written, and all those 
tricks just trip up more junior teammates--and often even myself. :)


David

Agreed, in fact, I decided to create a new style naming convention where 
_ref is always suffixed to variable names that are references, along 
with doing the unset, just in case. This goes to show that references 
can be a recipe for subtle bugs to creep in, so best to isolate them as 
much as possible to their own convention. If the convention is followed, 
it should eliminate the possibility of this bug, even if the unset is 
left out.


Tim


Re: [PHP] Strange foreach reference issue

2012-01-08 Thread Adi Mutu
You can see here some nice pics, it's exactly as you said.

http://schlueters.de/blog/archives/141-References-and-foreach.html




 From: Tim Behrendsen t...@behrendsen.com
To: php-general@lists.php.net 
Cc: Stephen stephe...@rogers.com; Matijn Woudt tijn...@gmail.com 
Sent: Sunday, January 8, 2012 3:01 AM
Subject: Re: [PHP] Strange foreach reference issue
 
On 1/7/2012 4:44 PM, Stephen wrote:
 On 12-01-07 07:30 PM, Tim Behrendsen wrote:
 
 When you use an ampersand on the variable, that creates a reference to the 
 array elements, allowing you to potentially change the array elements 
 themselves (which I'm not doing here).
 
 http://www.php.net/manual/en/control-structures.foreach.php
 
 I do notice in the manual that it says, Reference of a $value and the last 
 array element remain even after the foreach loop. It is recommended to 
 destroy it by unset(). But that doesn't really explain why it contaminates 
 the next foreach loop in such an odd way. You would think that the $row in 
 the second loop would be assigned a non-reference value.
 
 Tim
 
 Tim,
 
 You are using the $variable in an unintended (by PHP designers), and I 
 suggest undefined manner.
 
 So the outcome cannot, but definition be explained.
 
 Was this intended, and what were you trying to accomplish?
 
 Stephen

In the real code, I just happen to use the same variable name first as a 
reference, and then as a normal non-reference, and was getting the mysterious 
duplicate rows.

I think I'm using everything in a completely reasonable way; the second foreach 
is reassigning the loop variable. Nothing that comes before using that variable 
ought to cause undefined behavior. The warning in the manual is about using the 
loop variable as a reference after exiting the loop, but I'm not doing that. 
I'm reassigning it, exactly as if I just decided to do a straight assignment of 
$row

Ah ha, wait a minute, that's the key. OK, this is making more sense.

The first loop is leaving a reference to the final element. But then the second 
foreach is doing a straight assignment to the $row variable, but $row is a 
reference to the final element. So the foreach is assigning its iterated value 
to the final element of the array, instead of a normal variable.

OK, I understand the logic now. The world now makes sense. The moral is always 
unset the iterator variable when doing foreach with a reference, like the 
manual says. :)

Thanks for everyone's help.

Tim

-- PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

[PHP] Strange foreach reference issue

2012-01-07 Thread Tim Behrendsen

Hello,

This sure looks like a bug, but maybe there's some subtlety going on 
that I don't understand, so I would appreciate some insight. After much 
debugging, I tracked down a bug in my code to this test program. My PHP 
version is 5.3.3, running under Fedora Linux.


?php
$row_list = array(
array(
'Title' = 'Title #1',
),
array(
'Title' = 'Title #2',
),
array(
'Title' = 'Title #3',
) );

printRows at start:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title A $idx: {$row['Title']}\n;
}

printRows are now:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title B $idx: {$row['Title']}\n;
}
?

When you run the program, it gives the following output:

--
   Rows at start: Array
(
[0] = Array
(
[Title] = Title #1
)

[1] = Array
(
[Title] = Title #2
)

[2] = Array
(
[Title] = Title #3
)

)
Title A 0: Title #1
Title A 1: Title #2
Title A 2: Title #3
   Rows are now: Array
(
[0] = Array
(
[Title] = Title #1
)

[1] = Array
(
[Title] = Title #2
)

[2] = Array
(
[Title] = Title #3
)

)
Title B 0: Title #1
Title B 1: Title #2
Title B 2: Title #2
--

Note that the second foreach repeats the second row, even though the 
index is correct and the print_r shows things as correct.


Now, if you change the name of the reference variable from '$row' to 
'$rowx' (for example), things will work. So clearly there's some issue 
with $row being previously used as a reference that's contaminating 
the subsequent use of $row in the foreach. If there's some logic to 
this, it's escaping me.


Any insight on this would be appreciated.

Regards,

Tim Behrendsen




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-07 Thread Stephen

I cut and pasted your code and got the same result.

I flipped the two foreach blocks and got the expected results.

I deleted the first block and copied the second, then updated the 
string. I got this. I can't explain.


?php
$row_list = array(
array(
'Title' = 'Title #1',
),
array(
'Title' = 'Title #2',
),
array(
'Title' = 'Title #3',
) );

  printRows are:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title A $idx: {$row['Title']}\n;
}

  printRows are now:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title B $idx: {$row['Title']}\n;
}

   Rows are: Array
(
[0] =  Array
(
[Title] =  Title #1
)

[1] =  Array
(
[Title] =  Title #2
)

[2] =  Array
(
[Title] =  Title #3
)

)
Title A 0: Title #1
Title A 1: Title #2
Title A 2: Title #3
   Rows are now: Array
(
[0] =  Array
(
[Title] =  Title #1
)

[1] =  Array
(
[Title] =  Title #2
)

[2] =  Array
(
[Title] =  Title #3
)

)
Title B 0: Title #1
Title B 1: Title #2
Title B 2: Title #3



On 12-01-07 06:29 PM, Tim Behrendsen wrote:

Hello,

This sure looks like a bug, but maybe there's some subtlety going on 
that I don't understand, so I would appreciate some insight. After 
much debugging, I tracked down a bug in my code to this test program. 
My PHP version is 5.3.3, running under Fedora Linux.


?php
$row_list = array(
array(
'Title' = 'Title #1',
),
array(
'Title' = 'Title #2',
),
array(
'Title' = 'Title #3',
) );

printRows at start:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title A $idx: {$row['Title']}\n;
}

printRows are now:  . print_r($row_list, true);
foreach ($row_list as $idx = $row) {
print Title B $idx: {$row['Title']}\n;
}
?

When you run the program, it gives the following output:

--
   Rows at start: Array
(
[0] = Array
(
[Title] = Title #1
)

[1] = Array
(
[Title] = Title #2
)

[2] = Array
(
[Title] = Title #3
)

)
Title A 0: Title #1
Title A 1: Title #2
Title A 2: Title #3
   Rows are now: Array
(
[0] = Array
(
[Title] = Title #1
)

[1] = Array
(
[Title] = Title #2
)

[2] = Array
(
[Title] = Title #3
)

)
Title B 0: Title #1
Title B 1: Title #2
Title B 2: Title #2
--

Note that the second foreach repeats the second row, even though the 
index is correct and the print_r shows things as correct.


Now, if you change the name of the reference variable from '$row' to 
'$rowx' (for example), things will work. So clearly there's some issue 
with $row being previously used as a reference that's contaminating 
the subsequent use of $row in the foreach. If there's some logic to 
this, it's escaping me.


Any insight on this would be appreciated.

Regards,

Tim Behrendsen







--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-07 Thread Matijn Woudt
On Sun, Jan 8, 2012 at 12:29 AM, Tim Behrendsen t...@behrendsen.com wrote:
 Hello,

 This sure looks like a bug, but maybe there's some subtlety going on that I
 don't understand, so I would appreciate some insight. After much debugging,
 I tracked down a bug in my code to this test program. My PHP version is
 5.3.3, running under Fedora Linux.

 ?php
    $row_list = array(
        array(
            'Title' = 'Title #1',
        ),
        array(
            'Title' = 'Title #2',
        ),
        array(
            'Title' = 'Title #3',
        ) );

    print    Rows at start:  . print_r($row_list, true);
    foreach ($row_list as $idx = $row) {

Why is there an '' before $row here? That seems like the problem to me..

Matijn

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-07 Thread Tim Behrendsen

On 1/7/2012 4:18 PM, Matijn Woudt wrote:

On Sun, Jan 8, 2012 at 12:29 AM, Tim Behrendsent...@behrendsen.com  wrote:

Hello,

This sure looks like a bug, but maybe there's some subtlety going on that I
don't understand, so I would appreciate some insight. After much debugging,
I tracked down a bug in my code to this test program. My PHP version is
5.3.3, running under Fedora Linux.

?php
$row_list = array(
array(
'Title' =  'Title #1',
),
array(
'Title' =  'Title #2',
),
array(
'Title' =  'Title #3',
) );

printRows at start:  . print_r($row_list, true);
foreach ($row_list as $idx =  $row) {

Why is there an '' before $row here? That seems like the problem to me..

Matijn


When you use an ampersand on the variable, that creates a reference to 
the array elements, allowing you to potentially change the array 
elements themselves (which I'm not doing here).


http://www.php.net/manual/en/control-structures.foreach.php

I do notice in the manual that it says, Reference of a $value and the 
last array element remain even after the foreach loop. It is recommended 
to destroy it by unset(). But that doesn't really explain why it 
contaminates the next foreach loop in such an odd way. You would think 
that the $row in the second loop would be assigned a non-reference value.


Tim

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-07 Thread Stephen

On 12-01-07 07:30 PM, Tim Behrendsen wrote:


When you use an ampersand on the variable, that creates a reference to 
the array elements, allowing you to potentially change the array 
elements themselves (which I'm not doing here).


http://www.php.net/manual/en/control-structures.foreach.php

I do notice in the manual that it says, Reference of a $value and the 
last array element remain even after the foreach loop. It is 
recommended to destroy it by unset(). But that doesn't really explain 
why it contaminates the next foreach loop in such an odd way. You 
would think that the $row in the second loop would be assigned a 
non-reference value.


Tim


Tim,

You are using the $variable in an unintended (by PHP designers), and I 
suggest undefined manner.


So the outcome cannot, but definition be explained.

Was this intended, and what were you trying to accomplish?

Stephen

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Strange foreach reference issue

2012-01-07 Thread Tim Behrendsen

On 1/7/2012 4:44 PM, Stephen wrote:

On 12-01-07 07:30 PM, Tim Behrendsen wrote:


When you use an ampersand on the variable, that creates a reference 
to the array elements, allowing you to potentially change the array 
elements themselves (which I'm not doing here).


http://www.php.net/manual/en/control-structures.foreach.php

I do notice in the manual that it says, Reference of a $value and 
the last array element remain even after the foreach loop. It is 
recommended to destroy it by unset(). But that doesn't really 
explain why it contaminates the next foreach loop in such an odd way. 
You would think that the $row in the second loop would be assigned a 
non-reference value.


Tim


Tim,

You are using the $variable in an unintended (by PHP designers), and 
I suggest undefined manner.


So the outcome cannot, but definition be explained.

Was this intended, and what were you trying to accomplish?

Stephen


In the real code, I just happen to use the same variable name first as a 
reference, and then as a normal non-reference, and was getting the 
mysterious duplicate rows.


I think I'm using everything in a completely reasonable way; the second 
foreach is reassigning the loop variable. Nothing that comes before 
using that variable ought to cause undefined behavior. The warning in 
the manual is about using the loop variable as a reference after exiting 
the loop, but I'm not doing that. I'm reassigning it, exactly as if I 
just decided to do a straight assignment of $row


Ah ha, wait a minute, that's the key. OK, this is making more sense.

The first loop is leaving a reference to the final element. But then the 
second foreach is doing a straight assignment to the $row variable, but 
$row is a reference to the final element. So the foreach is assigning 
its iterated value to the final element of the array, instead of a 
normal variable.


OK, I understand the logic now. The world now makes sense. The moral is 
always unset the iterator variable when doing foreach with a reference, 
like the manual says. :)


Thanks for everyone's help.

Tim

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Possible foreach bug; seeking advice to isolate the problem

2010-10-22 Thread Ford, Mike
 -Original Message-
 From: Jonathan Sachs [mailto:081...@jhsachs.com]
 Sent: 20 October 2010 04:48
 To: php-general@lists.php.net
 Subject: [PHP] Possible foreach bug; seeking advice to isolate the
 problem
 
 I've got a script which originally contained the following piece of
 code:
 
 foreach ( $objs as $obj ) {
do_some_stuff($obj);
 }
 
 When I tested it, I found that on every iteration of the loop the
 last
 element of $objs was assigned the value of the current element. I
 was
 able to step through the loop and watch this happening, element by
 element.

All the other suggestions I've seen on this are essentially correct -- before 
the foreach runs, something somewhere has set $obj to be a reference to the 
last element of the array.

 It really doesn't matter whether you can find the culprit for this or not -- 
the solution is simply to put an

  unset($obj)

immediately before the foreach statement -- this will break the reference 
(without destroying anything but $obj!) and make the foreach behave exactly as 
you want.

Cheers!

Mike

 -- 
Mike Ford,
Electronic Information Developer, Libraries and Learning Innovation,  
Leeds Metropolitan University, C507 City Campus, 
Woodhouse Lane, LEEDS,  LS1 3HE,  United Kingdom 
Email: m.f...@leedsmet.ac.uk 
Tel: +44 113 812 4730





To view the terms under which this email is distributed, please go to 
http://disclaimer.leedsmet.ac.uk/email.htm

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Possible foreach bug; seeking advice to isolate the problem

2010-10-20 Thread richard gray

 On 20/10/2010 05:47, Jonathan Sachs wrote:

I've got a script which originally contained the following piece of
code:

foreach ( $objs as $obj ) {
do_some_stuff($obj);
}

When I tested it, I found that on every iteration of the loop the last
element of $objs was assigned the value of the current element. I was
able to step through the loop and watch this happening, element by
element.


Are you are using a 'referencing' foreach? i.e.

foreach ($objs as $obj) {
do_some_stuff($obj);
}

or is the above code a direct lift from your script?

Referencing foreach statements can cause problems as the reference to 
the last array entry is persistent after the foreach loop has terminated 
so any further foreach statements on the same array will overwrite the 
previous reference which is still pointing to the last item.


Rich


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Possible foreach bug; seeking advice to isolate the problem

2010-10-19 Thread Jonathan Sachs
I've got a script which originally contained the following piece of
code:

foreach ( $objs as $obj ) {
   do_some_stuff($obj);
}

When I tested it, I found that on every iteration of the loop the last
element of $objs was assigned the value of the current element. I was
able to step through the loop and watch this happening, element by
element.

I originally encountered this problem using PHP v5.2.4 under Windows
XP. I later reproduced it in v5.3.2 under XP.

The function call wasn't doing it. I replaced the function call with
an echo statement and got the same result.

For my immediate needs, I evaded the problem by changing the foreach
loop to a for loop that references elements of $objs by subscript.

That leaves me with the question: what is going wrong with foreach?
I'm trying to either demonstrate that it's my error, not the PHP
engine's, or isolate the problem in a small script that I can submit
with a bug report. The current script isn't suitable for that because
it builds $objs by reading a database table and doing some rather
elaborate manipulations of the data.

I tried to eliminate the database by doing a var_export of the array
after I built it, then assigning the exported expression to a variable
immediately before the foreach. That broke the bug -- the loop
behaved correctly.

There's a report of a bug that looks similar in the comments section
of php.net's manual page for foreach, time stamped 09-Jul-2009 11:50.
As far as I can tell it was never submitted as a bug and was never
resolved. I sent an inquiry to the author but he didn't respond.

Can anyone make suggestions on this -- either insights into what's
wrong, or suggestions for producing a portable, reproducible example?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-11 Thread tedd

At 3:46 PM -0400 6/10/10, Paul M Foster wrote:

On Thu, Jun 10, 2010 at 11:16:08AM -0400, tedd wrote:

  I spend much of my time thinking Did I do that before?

grin I know the feeling. I will say this, though. I have yet to figure
out, from your URLs, how your site(s) is/are organized. Maybe a reorg
would help?

Paul


Paul:

Unfortunately, I really don't follow an organization plan for my 
demos on any of my sites (well over a dozen now).


Please understand that when I started creating demos, I only wanted 
to see how a specific thing worked. I had no idea that this 
investigation would become a giant listing of stuff.


I could explain how I can easily create demos if you want, but it's 
pretty basic stuff using includes for a common header/footer files 
leaving only the specific of the topic to be added. The hard part is 
just finding a layout that you like -- after that it's pretty easy to 
duplicate it each time you want to demo something.


I will be updating my sperling.com soon to add in language specific 
code (php/css/js) -- and that *will* be organized into categories. 
However, that may be down the road because I have a few other 
pressing matters that are pulling me in several different directions.


Cheers,

tedd

--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-10 Thread tedd

At 7:19 AM +0530 6/10/10, Shreyas wrote:

PHP'ers,

I am reading a PHP book which explains foreach and at the end says : *'When
foreach starts walking through an array, it moves the pointer to
the beginning of the array. You don't need to reset an array before
walking through it with foreach.'*
*
*
*Does this mean - *
*1) Before I navigate the array, foreach will bring the pointer to the
starting key?*
*2) After the first index, it goes to 2nd, 3rd, and nth? *


Regards,
Shreyas


Shreyas:

This is one of those questions that you can test very easily, just 
initialize an array and try it.


?php

$test = array(a, b, c, d);
foreach ($test as $value)
   {
   echo(value = $value br);
   }

?

As the references show, there are two versions of the foreach, the 
one above and this:


?php

$test = array(a, b, c, d);
foreach ($test as $key = $value)
   {
   echo($key= $key  value=$value br);
   }

?

Note that you can pull-out the index (i.e., $key) as well as the 
value (i.e., $value) of each index. The br is only to add a 
linefeed in html.


This is a bit easier than using a for() loop.

Cheers,

tedd
--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-10 Thread Paul M Foster
On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:

 At 7:19 AM +0530 6/10/10, Shreyas wrote:
 PHP'ers,

 I am reading a PHP book which explains foreach and at the end says : *'When
 foreach starts walking through an array, it moves the pointer to
 the beginning of the array. You don't need to reset an array before
 walking through it with foreach.'*
 *
 *
 *Does this mean - *
 *1) Before I navigate the array, foreach will bring the pointer to the
 starting key?*
 *2) After the first index, it goes to 2nd, 3rd, and nth? *


 Regards,
 Shreyas

 Shreyas:

 This is one of those questions that you can test very easily, just
 initialize an array and try it.

+1

This is Tedd's modus operandi. His website(s) are full of exactly this
type of thing. And I have to agree. I can't count the number of
questions I *haven't* asked on this list, because I built a page to test
a particular concept. And this sort of activity (as opposed to just
reading about something) really locks in your understanding of a
concept.

Paul

-- 
Paul M. Foster

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-10 Thread Shreyas
All,

I tried and tested it but wanted a solid confirmation on it. I felt foreach
usage is better than manual way of next(), prev() et al.

Thanks for the comments. I consider the thread answered and solved unless
someone has anything more to add.

Regards,
Shreyas

On Thu, Jun 10, 2010 at 7:02 PM, Paul M Foster pa...@quillandmouse.comwrote:

 On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:

  At 7:19 AM +0530 6/10/10, Shreyas wrote:
  PHP'ers,
 
  I am reading a PHP book which explains foreach and at the end says :
 *'When
  foreach starts walking through an array, it moves the pointer to
  the beginning of the array. You don't need to reset an array before
  walking through it with foreach.'*
  *
  *
  *Does this mean - *
  *1) Before I navigate the array, foreach will bring the pointer to the
  starting key?*
  *2) After the first index, it goes to 2nd, 3rd, and nth? *
 
 
  Regards,
  Shreyas
 
  Shreyas:
 
  This is one of those questions that you can test very easily, just
  initialize an array and try it.

 +1

 This is Tedd's modus operandi. His website(s) are full of exactly this
 type of thing. And I have to agree. I can't count the number of
 questions I *haven't* asked on this list, because I built a page to test
 a particular concept. And this sort of activity (as opposed to just
 reading about something) really locks in your understanding of a
 concept.

 Paul

 --
 Paul M. Foster

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
Regards,
Shreyas


Re: [PHP] Question - foreach.

2010-06-10 Thread tedd

At 9:32 AM -0400 6/10/10, Paul M Foster wrote:

On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:

  This is one of those questions that you can test very easily, just

 initialize an array and try it.


+1

This is Tedd's modus operandi. His website(s) are full of exactly this
type of thing. And I have to agree. I can't count the number of
questions I *haven't* asked on this list, because I built a page to test
a particular concept. And this sort of activity (as opposed to just
reading about something) really locks in your understanding of a
concept.

Paul


Paul:

Now, if I could get the old memory to lock in and remember it, it 
would be great!


I spend much of my time thinking Did I do that before?

Cheers,

tedd
--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-10 Thread Paul M Foster
On Thu, Jun 10, 2010 at 11:16:08AM -0400, tedd wrote:

 At 9:32 AM -0400 6/10/10, Paul M Foster wrote:
 On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:

   This is one of those questions that you can test very easily, just
  initialize an array and try it.

 +1

 This is Tedd's modus operandi. His website(s) are full of exactly this
 type of thing. And I have to agree. I can't count the number of
 questions I *haven't* asked on this list, because I built a page to test
 a particular concept. And this sort of activity (as opposed to just
 reading about something) really locks in your understanding of a
 concept.

 Paul

 Paul:

 Now, if I could get the old memory to lock in and remember it, it
 would be great!

 I spend much of my time thinking Did I do that before?

grin I know the feeling. I will say this, though. I have yet to figure
out, from your URLs, how your site(s) is/are organized. Maybe a reorg
would help?

Paul

-- 
Paul M. Foster

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Question - foreach.

2010-06-10 Thread Bob McConnell
From: Paul M Foster

 On Thu, Jun 10, 2010 at 11:16:08AM -0400, tedd wrote:

 At 9:32 AM -0400 6/10/10, Paul M Foster wrote:
 On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:


 Paul:

 Now, if I could get the old memory to lock in and remember it, it
 would be great!

 I spend much of my time thinking Did I do that before?
 
 grin I know the feeling. I will say this, though. I have yet to
figure
 out, from your URLs, how your site(s) is/are organized. Maybe a reorg
 would help?

ISTR there are three signs of old age. The first is loss of memory, but
I can never remember the other two.

Bob McConnell

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-10 Thread David McGlone
On Thursday 10 June 2010 11:16:08 tedd wrote:
 At 9:32 AM -0400 6/10/10, Paul M Foster wrote:
 On Thu, Jun 10, 2010 at 07:03:28AM -0400, tedd wrote:
This is one of those questions that you can test very easily, just
   
   initialize an array and try it.
 
 +1
 
 This is Tedd's modus operandi. His website(s) are full of exactly this
 type of thing. And I have to agree. I can't count the number of
 questions I *haven't* asked on this list, because I built a page to test
 a particular concept. And this sort of activity (as opposed to just
 reading about something) really locks in your understanding of a
 concept.
 
 Paul
 
 Paul:
 
 Now, if I could get the old memory to lock in and remember it, it
 would be great!
 
 I spend much of my time thinking Did I do that before?

Looks like you and I are in the same boat! My memory these days has went to 
the dumps.

Although I do the same thing Paul does to actually grasp a more in depth 
understanding of something, sometimes in a day or two it's often forgotten.

-- 
Blessings,
David M.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Question - foreach.

2010-06-09 Thread Shreyas
PHP'ers,

I am reading a PHP book which explains foreach and at the end says : *'When
foreach starts walking through an array, it moves the pointer to
the beginning of the array. You don’t need to reset an array before
walking through it with foreach.'*
*
*
*Does this mean - *
*1) Before I navigate the array, foreach will bring the pointer to the
starting key?*
*2) After the first index, it goes to 2nd, 3rd, and nth? *


Regards,
Shreyas


Re: [PHP] Question - foreach.

2010-06-09 Thread Adam Richardson
On Wed, Jun 9, 2010 at 9:49 PM, Shreyas shreya...@gmail.com wrote:

 PHP'ers,

 I am reading a PHP book which explains foreach and at the end says : *'When
 foreach starts walking through an array, it moves the pointer to
 the beginning of the array. You don’t need to reset an array before
 walking through it with foreach.'*
 *
 *
 *Does this mean - *
 *1) Before I navigate the array, foreach will bring the pointer to the
 starting key?*
 *2) After the first index, it goes to 2nd, 3rd, and nth? *


 Regards,
 Shreyas


Number 1.

Adam

-- 
Nephtali:  PHP web framework that functions beautifully
http://nephtaliproject.com


Re: [PHP] Question - foreach.

2010-06-09 Thread Jim Lucas

Shreyas wrote:

PHP'ers,

I am reading a PHP book which explains foreach and at the end says : *'When
foreach starts walking through an array, it moves the pointer to
the beginning of the array. You don’t need to reset an array before
walking through it with foreach.'*
*
*
*Does this mean - *
*1) Before I navigate the array, foreach will bring the pointer to the
starting key?*
*2) After the first index, it goes to 2nd, 3rd, and nth? *


Regards,
Shreyas



Here is your best reference:

http://php.net/foreach

Look at the two Notes sections on the top of the page.

The first says this:

Note: When foreach first starts executing, the internal array pointer is 
automatically reset to the first element of the array. This means that 
you do not need to call reset()  before a foreach  loop.


Basically what you said.  But then the second says this

Note: Unless the array is referenced, foreach operates on a copy of the 
specified array and not the array itself. foreach  has some side effects 
on the array pointer. Don't rely on the array pointer during or after 
the foreach without resetting it.


--
Jim Lucas

A: Maybe because some people are too annoyed by top-posting.
Q: Why do I not get an answer to my question(s)?
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Question - foreach.

2010-06-09 Thread Daniel Brown
On Wed, Jun 9, 2010 at 21:49, Shreyas shreya...@gmail.com wrote:
 PHP'ers,

 I am reading a PHP book which explains foreach and at the end says : *'When
 foreach starts walking through an array, it moves the pointer to
 the beginning of the array. You don’t need to reset an array before
 walking through it with foreach.'*
 *
 *
 *Does this mean - *
[snip!]

An easy way to think about it: foreach is cocky and doesn't give a
damn about the rules array functions or placements have set in place.
It'll start from the beginning, and to hell with everyone else.

In other words: foreach will iterate wholly; it will count *for*
*each* key in the loop, not just where another portion of the code
left off.

-- 
/Daniel P. Brown
daniel.br...@parasane.net || danbr...@php.net
http://www.parasane.net/ || http://www.pilotpig.net/
We now offer SAME-DAY SETUP on a new line of servers!

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-12 Thread Ashley Sheridan
On Tue, 2009-08-11 at 16:00 -0400, Eddie Drapkin wrote:
 On Tue, Aug 11, 2009 at 3:56 PM, teddtedd.sperl...@gmail.com wrote:
  At 12:44 PM -0700 8/11/09, Ben Dunlap wrote:
 
  This is probably flame-war tinder, so I'll try to tread more delicately in
  the future. Next you know we'll be on the ternary operator and which is
  better, Mac or Windows. ;-)
 
  Ben
 
  That was won long ago, it's Mac. :-)
 
  Cheers,
 
  tedd
 
  --
  ---
  http://sperling.com  http://ancientstones.com  http://earthstones.com
 
  --
  PHP General Mailing List (http://www.php.net/)
  To unsubscribe, visit: http://www.php.net/unsub.php
 
 
 
 If by Mac you mean Linux, you're entirely correct.
 
Linux +100

Thanks,
Ash
http://www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-12 Thread Ashley Sheridan
On Tue, 2009-08-11 at 16:23 -0400, Rick Duval wrote:
 OK, first guys, I'm sorry to have to do this but I can't get off this list!!!
 
 I've followed the instructions on a couple of occasions (the ones at
 the bottom of every email):
  PHP General Mailing List (http://www.php.net/)
  To unsubscribe, visit: http://www.php.net/unsub.php
 
 Been There, done that. I can't get off the list!!! I use Gmail and I
 use an an alias as well, tried them both, still on the list. No reply
 from Majordomo.
 
 Yes, I've check my spam filter for a unsubscribe confirmation (if it
 sends one which I presume it's supposed to).
 
 Headers tell me that this list is php-general@lists.php.net. Sent
 the unsubscribe emails. No replies.
 
 Again. I apologize but have no idea what to do to get off this list!
 THis is the only list server I can't seem to get off of.
 
 Help!
 
 
 On Mon, Aug 10, 2009 at 6:04 PM, John
 Butlergovinda.webdnat...@gmail.com wrote:
  I can't seem to get my foreach loops to work, will PHP parse embedded
  loops?
 
  yes.
 
  Is this something I need to have in a database to work?
 
  no, you can do it with the arrays...  but it may be easier to work with over
  the long run if that data was in a db.
 
  Anyway right after you finish creating the array and it's embedded arrays,
  in your code, then add this:
  var_dump($shows); //--so you can see what you just created.  If it looks
  right, THEN go on bothering to try and parse it with your (embedded)
  foreach's {
 
  
  John Butler (Govinda)
  govinda.webdnat...@gmail.com
 
 
 
 
  --
  PHP General Mailing List (http://www.php.net/)
  To unsubscribe, visit: http://www.php.net/unsub.php
 
 
  -This message has been scanned for
  viruses and dangerous content byAccurate Anti-Spam Technologies.
  www.AccurateAntiSpam.com
 
 
 
Use the unsubscribe email address that's in the header (this is very
different from the footer) of every email from the list.

Thanks,
Ash
http://www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread hessiess
Do *NOT* get into the habit of outputting your HTML using echo or print
statements, it becomes unmaintainable very quickly, use a templating
language, ether with a framework(recomended) or standalone.

You should learn the basics of HTML and CSS, go and read
http://htmldog.com/, btw to add a newline you need to use br /.

 I am using the print function to display my html. I cannot get the
 line return ( \n ) character to actually push the html onto the next
 line, it just gets displayed instead. Should I be using echo?


 Allen, you off and running again?

 echo blah..  \n; //-- this will print  the literal 'blah..  '  and
 then a newline into your HTML *source code*
 echo 'blah..  \n'; //-- this will print the literal 'blah..  \n' into
 your HTML *source code*

 IIRC print is the same as echo.  That is not your apparent issue.

 Say if you are stuck again, and on what exactly.

 -John

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Ashley Sheridan
On Tue, 2009-08-11 at 07:13 +, hessi...@hessiess.com wrote:
 Do *NOT* get into the habit of outputting your HTML using echo or print
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.
 
 You should learn the basics of HTML and CSS, go and read
 http://htmldog.com/, btw to add a newline you need to use br /.
 
  I am using the print function to display my html. I cannot get the
  line return ( \n ) character to actually push the html onto the next
  line, it just gets displayed instead. Should I be using echo?
 
 
  Allen, you off and running again?
 
  echo blah..  \n; //-- this will print  the literal 'blah..  '  and
  then a newline into your HTML *source code*
  echo 'blah..  \n'; //-- this will print the literal 'blah..  \n' into
  your HTML *source code*
 
  IIRC print is the same as echo.  That is not your apparent issue.
 
  Say if you are stuck again, and on what exactly.
 
  -John
 
  --
  PHP General Mailing List (http://www.php.net/)
  To unsubscribe, visit: http://www.php.net/unsub.php
 
 
 
 

*Or* you could use the heredoc syntax, which I'm quite a fan of.

print EOC
psome content here/p
pcontent with a php $variable here/p


pthis gets displayed after the extra new lines in the source/p
EOC;

Still easy to maintain.

Thanks,
Ash
http://www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread sono-io


On Aug 11, 2009, at 12:13 AM, hessi...@hessiess.com wrote:

Do *NOT* get into the habit of outputting your HTML using echo or  
print

statements, it becomes unmaintainable very quickly, use a templating
language, ether with a framework(recomended) or standalone.


	This sounds interesting.  Could you expound on this a little more and  
perhaps list a couple of the templates you mention?


Thanks,
Frank

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Ben Dunlap
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.


But he /is/ using a templating language... PHP. ;-)

Ben


Re: [PHP] Embedding foreach loops

2009-08-11 Thread Robert Cummings



Ben Dunlap wrote:

statements, it becomes unmaintainable very quickly, use a templating
language, ether with a framework(recomended) or standalone.



But he /is/ using a templating language... PHP. ;-)


Keep telling yourself that... and be sure to pat your own back.

Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread hessiess

 On Aug 11, 2009, at 12:13 AM, hessi...@hessiess.com wrote:

 Do *NOT* get into the habit of outputting your HTML using echo or
 print
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.

 This sounds interesting.  Could you expound on this a little
more and
 perhaps list a couple of the templates you mention?

 Thanks,
 Frank


There are a number of options for templating in PHP such as smarty, Dwoo
and PHP itself, though the syntax can be rather messy. Personally I just
use a simple find and replace macro system to expand custom short-hand
code into the more verbose PHP, then run it through exec and capture the
result to a variable with output buffering, the class folows:

?php
class view
{
var $str;

/*++
* Load in template file and expand macros into PHP
++*/
function __CONSTRUCT($tplname)
{
$fh = fopen($tplname, 'r');
$this-str = fread($fh, filesize($tplname));
fclose($fh);

$this-expand_macros();
}

/*++
 * Run the template and return a variable
++*/
public function parse_to_variable($array = array())
{
extract($array);

ob_start();
eval($this-str);
$result = ob_get_contents();
ob_end_clean();
return $result;
}

/*++
* Expand macros into PHP
++*/
private function expand_macros()
{
// Expand if macro
$this-str = str_replace(if, ?php if, $this-str);
$this-str = str_replace(eif~, ?php endif;?, $this-str);

// Expand loop macro
$this-str = str_replace(loop, ?php foreach, $this-str);
$this-str = str_replace(eloop~, ?php endforeach;?,
$this-str);

// Expand display macro
$this-str = str_replace(dsp, ?php echo, $this-str);

// Expand end tag macro
$this-str = str_replace(~, ?, $this-str);

// Add PHP close tag to exit PHP mode
$this-str = ? . $this-str;
}
}


This loads template files like the folowing:
form enctype=multipart/form-data action=dsp $upload_url ~
method=post
pinput type=hidden name=MAX_FILE_SIZE value=900 //p
pUpload new file, max size dsp $max ~:/p
p
input name=uploaded_file type=file /
input type=submit value=Send File /
/p
/form

table
tr
th width=180pxFilename/th
th width=60pxLink/th
th width=90pxSize (KB)/th
th width=50pxDelete/th
tr

loop ($files as $file): ~

tr
tddsp $file['Name'] ~/td
tda href=dsp $file['Path'] ~Link/a/td
tddsp $file['Size'] / 1000 ~/td
tda href=dsp $file['d_url'] ~X/a/td
tr
eloop~
/table

---
And it can be used like this

$dialogue = new view(template/file_display.tpl);
$dialogue = $dialogue - parse_to_variable(array(
'upload_url' = $upload_url,
'max' = $max_size,
'files' = $files));

the $dialogue var now contains the compiled template, ready for displaying
or integrating into another template.


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Ben Dunlap
 statements, it becomes unmaintainable very quickly, use a templating
 language, ether with a framework(recomended) or standalone.



 But he /is/ using a templating language... PHP. ;-)


 Keep telling yourself that... and be sure to pat your own back.


I'm sure there are plenty of situations that call for a more focused
templating system than the one that PHP already is. And there are plenty
that don't.

From the earlier content of this thread, I suspect the problem the OP is
currently working on falls into the latter camp. Didn't mean to bash
templating systems.

This is probably flame-war tinder, so I'll try to tread more delicately in
the future. Next you know we'll be on the ternary operator and which is
better, Mac or Windows. ;-)

Ben


Re: [PHP] Embedding foreach loops

2009-08-11 Thread tedd

At 12:44 PM -0700 8/11/09, Ben Dunlap wrote:

This is probably flame-war tinder, so I'll try to tread more delicately in
the future. Next you know we'll be on the ternary operator and which is
better, Mac or Windows. ;-)

Ben


That was won long ago, it's Mac. :-)

Cheers,

tedd

--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Eddie Drapkin
On Tue, Aug 11, 2009 at 3:56 PM, teddtedd.sperl...@gmail.com wrote:
 At 12:44 PM -0700 8/11/09, Ben Dunlap wrote:

 This is probably flame-war tinder, so I'll try to tread more delicately in
 the future. Next you know we'll be on the ternary operator and which is
 better, Mac or Windows. ;-)

 Ben

 That was won long ago, it's Mac. :-)

 Cheers,

 tedd

 --
 ---
 http://sperling.com  http://ancientstones.com  http://earthstones.com

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



If by Mac you mean Linux, you're entirely correct.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread John Butler

Allen, you off and running again?


Sure am, thanks, on to the next set of issues. Seems like  
programming is always moving on from one error to the next :)


Currently, I am having trouble with echo and php line-returns.

It works on one part of the code, but not on another (instead,  
prints it to html).


For example:

[code]

$show[show_01][price] * $show_01_qty = $Total_show_01;
 echo \ntr\n\t;
 echo tda.$show[show_01][price]./td/n/ttd*/td/n/ttdb. 
$show_01_qty./td/n/ttd=/td\n\ttdc.$Total_show_01./td;

 echo \n/tr;

[/code]

outputs this html

[code]

tr
   tda/td/n/ttd*/td/n/ttdb/td/n/ttd=/td
   tdc/td
/tr

[/code]
Additionally, it won't display the variables, as you can see, even  
though they will echo out further above in the document. Odd...



well you escape a newline char with this slash:
\
and not this one:
/
notice you were not consistent with your use of them.
as for the array not being parsed inside your echo statement -  I  
don't see the issue by looking now.  Are you saying the EXACT same  
code does output the expected value for those array elements higher up  
the script?  Show us the code where it is working and again where it  
is not..  side by side (pasted just after each other in a new post to  
the list).


I assume you are past this next point, but always remember
var_dump($myArray);
is your friend.  Put it just before where you try to echo out some  
part of the array..  check to be sure the value is there is that  
element of the multi-dimensional array the way you think it is.


-John

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Rick Duval
OK, first guys, I'm sorry to have to do this but I can't get off this list!!!

I've followed the instructions on a couple of occasions (the ones at
the bottom of every email):
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php

Been There, done that. I can't get off the list!!! I use Gmail and I
use an an alias as well, tried them both, still on the list. No reply
from Majordomo.

Yes, I've check my spam filter for a unsubscribe confirmation (if it
sends one which I presume it's supposed to).

Headers tell me that this list is php-general@lists.php.net. Sent
the unsubscribe emails. No replies.

Again. I apologize but have no idea what to do to get off this list!
THis is the only list server I can't seem to get off of.

Help!


On Mon, Aug 10, 2009 at 6:04 PM, John
Butlergovinda.webdnat...@gmail.com wrote:
 I can't seem to get my foreach loops to work, will PHP parse embedded
 loops?

 yes.

 Is this something I need to have in a database to work?

 no, you can do it with the arrays...  but it may be easier to work with over
 the long run if that data was in a db.

 Anyway right after you finish creating the array and it's embedded arrays,
 in your code, then add this:
 var_dump($shows); //--so you can see what you just created.  If it looks
 right, THEN go on bothering to try and parse it with your (embedded)
 foreach's {

 
 John Butler (Govinda)
 govinda.webdnat...@gmail.com




 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php


 -This message has been scanned for
 viruses and dangerous content byAccurate Anti-Spam Technologies.
 www.AccurateAntiSpam.com



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-11 Thread Robert Cummings

Let me be the first to welcome you to the list!!!



Rick Duval wrote:

OK, first guys, I'm sorry to have to do this but I can't get off this list!!!

I've followed the instructions on a couple of occasions (the ones at
the bottom of every email):

PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Been There, done that. I can't get off the list!!! I use Gmail and I
use an an alias as well, tried them both, still on the list. No reply
from Majordomo.

Yes, I've check my spam filter for a unsubscribe confirmation (if it
sends one which I presume it's supposed to).

Headers tell me that this list is php-general@lists.php.net. Sent
the unsubscribe emails. No replies.

Again. I apologize but have no idea what to do to get off this list!
THis is the only list server I can't seem to get off of.

Help!


On Mon, Aug 10, 2009 at 6:04 PM, John
Butlergovinda.webdnat...@gmail.com wrote:

I can't seem to get my foreach loops to work, will PHP parse embedded
loops?

yes.


Is this something I need to have in a database to work?

no, you can do it with the arrays...  but it may be easier to work with over
the long run if that data was in a db.

Anyway right after you finish creating the array and it's embedded arrays,
in your code, then add this:
var_dump($shows); //--so you can see what you just created.  If it looks
right, THEN go on bothering to try and parse it with your (embedded)
foreach's {


John Butler (Govinda)
govinda.webdnat...@gmail.com




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


-This message has been scanned for
viruses and dangerous content byAccurate Anti-Spam Technologies.
www.AccurateAntiSpam.com






--
http://www.interjinn.com
Application and Templating Framework for PHP

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedded foreach loops

2009-08-10 Thread John Butler


On Aug 10, 2009, at 3:43 PM, Jim Lucas wrote:


Allen McCabe wrote:
I am creating an order form for tickets for a list of performances  
at a

performing arts center.

Currently, the form is on paper, and is set up as follows:
-Nutcracker - Tues 10/13 - 11am - $4.00



Thanks for letting us know about your new order form.

Did you have a question about something?  Or simply wanted to let us  
know?


Jim


I was thinking free tickets!




Re: [PHP] Embedding foreach loops

2009-08-10 Thread Jonathan Tapicer
On Mon, Aug 10, 2009 at 6:44 PM, Allen McCabeallenmcc...@gmail.com wrote:
 Gmail automatically sent my last email, apologies.

 I am creating an order form for tickets for a list of performances at a
 performing arts center.

 Currently, the form is on paper, and is set up as follows:
 -Title     - date  - time - price - soldout - quantity - total($)
 -Nutcracker - Tues 10/13 -  9am - $4.00 - yes/no  -  - __
 -Nutcracker - Tues 10/13 - 11am - $4.00 - yes/no  -  - __
 -Mayhem P.. - Thur 01/21 -  9am - $4.00 - yes/no  -  - __
 -Mayhem P.. - Thur 01/21 - 11am - $4.00 - yes/no  -  - __
 -Max and... - Tues 04/21 -  9am - $4.00 - yes/no  -  - __

 A given show may have between 1 and 4 performances, and I figured the best
 way to approach this was to consider each show time for each show as an
 entity. There are 19 unique titles, but given different showtimes, it
 becomes 38 'shows'.

 I have the shows in an array ($shows), and the details for each show in its
 own array (eg. $show_01) embedded into the show array.

 I need to generate a row for each show (so 38 rows), and assign quantity and
 total input fields a unique name and id.

 I can't seem to get my foreach loops to work, will PHP parse embedded loops?

 Here is an example of my embedded arrays:

 [code=shows.php]

 $shows = array();

  $shows['show_01'] = $show_01;
  $show_01 = array();
  $show_01['title'] = 'Van Cliburn Gold Medal Winner';
  $show_01['date'] = 'Tues. 10/13/2009';
  $show_01['time'] = '11am';
  $show_01['price'] = 4.00;
  $show_01['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
 (without quotations).

  $shows['show_02'] = $show_02;
  $show_02 = array();
  $show_02['title'] = 'Jack and the Beanstalk';
  $show_02['date'] = 'Fri. 10/23/2009';
  $show_02['time'] = '11am';
  $show_02['price'] = 4.00;
  $show_02['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
 (without quotations).

 [/code]

 And here are the foreach loops I'm trying to build the rows with:

 [code=order.php]

 ?php
 foreach ($shows as $key = $value) {
  foreach ($value as $key2 = $value2) {
      print '      td bgcolor=#DD'. $value2 .'/td';
  }
  print 'trtd';
  print '      td colspan=3 bgcolor=#DDinput
 name='.$value.'_qty  type=text id='.$value.'_qty size=5  //td';
  print '      th bgcolor=#DDspan class=style6$/span';
  print '        input name='.$value.'_total  type=text
 id='.$value.'_total size=15 maxlength=6  //th';
  print '      th bgcolor=#DD class=instructyes/no/th';
  print '/tr';
 }
 ?

 [/code]

 In case you were wondering why I embedded the foreach statement, I need each
 array (eg. $show_22) to display in a row, and I need PHP to build as many
 rows are there are shows.

 Is this something I need to have in a database to work?

 Thanks!


Embedded loops are OK, actually I don't know a language where you can't do it :)

I think that your problem is the $shows array creation, you do this:

 $shows = array();

  $shows['show_01'] = $show_01;
  $show_01 = array();

Note that you are assigning $show_01 to a key in $shows before
creating $show_01, you should first create and fill $show_01 and then
assign it to a key in $shows.

Hope that helps.

Jonathan

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread John Butler
I can't seem to get my foreach loops to work, will PHP parse  
embedded loops?


yes.


Is this something I need to have in a database to work?


no, you can do it with the arrays...  but it may be easier to work  
with over the long run if that data was in a db.


Anyway right after you finish creating the array and it's embedded  
arrays, in your code, then add this:
var_dump($shows); //--so you can see what you just created.  If it  
looks right, THEN go on bothering to try and parse it with your  
(embedded) foreach's {



John Butler (Govinda)
govinda.webdnat...@gmail.com




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread Allen McCabe
John,

I did this, and got my arrays dumped (on one line). After adding line
returns, here is a snippet:

[code=array dump]

array(38) {
[show_01]= array(5) {
[title]= string(29) Van Cliburn Gold Medal Winner
[date]= string(16) Tues. 10/13/2009
[time]= string(4) 11am
[price]= float(4)
[soldout]= int(0)
}
[show_02]= array(5) {
[title]= string(22) Jack and the Beanstalk
[date]= string(15) Fri. 10/23/2009
[time]= string(4) 11am
[price]= float(4)
[soldout]= int(0)
}

[/code]

and for reference, my original php used to set up arrays

[code=shows.php]

$shows = array();
  $show_01 = array();
  $show_01['title'] = 'Van Cliburn Gold Medal Winner';
  $show_01['date'] = 'Tues. 10/13/2009';
  $show_01['time'] = '11am';
  $show_01['price'] = 4.00;
  $show_01['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
(without quotations).
 $shows['show_01'] = $show_01;
  $show_02 = array();
  $show_02['title'] = 'Jack and the Beanstalk';
  $show_02['date'] = 'Fri. 10/23/2009';
  $show_02['time'] = '11am';
  $show_02['price'] = 4.00;
  $show_02['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
(without quotations).
 $shows['show_02'] = $show_02;

[/code]

Does this dump look right?

On Mon, Aug 10, 2009 at 3:04 PM, John Butler
govinda.webdnat...@gmail.comwrote:

  I can't seem to get my foreach loops to work, will PHP parse embedded
 loops?


 yes.

 Is this something I need to have in a database to work?


 no, you can do it with the arrays...  but it may be easier to work with
 over the long run if that data was in a db.

 Anyway right after you finish creating the array and it's embedded arrays,
 in your code, then add this:
 var_dump($shows); //--so you can see what you just created.  If it looks
 right, THEN go on bothering to try and parse it with your (embedded)
 foreach's {

 
 John Butler (Govinda)
 govinda.webdnat...@gmail.com




 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Embedding foreach loops

2009-08-10 Thread John Butler


I did this, and got my arrays dumped (on one line). After adding  
line returns, here is a snippet:



it looks OK.  Note that you can see (copy/paste) that array which you  
just dumped, much better, if you view the source code of the html  
page.  OR you can use pre to make that format persist thru' to what  
you see without viewing the source., Like so:


echo hr /pre\n;
var_dump($theArray);
echo /pre\n;
echo hr /\n;

My brain is so full of my own work..  and I am newbie compared to most  
lurking here.. but I am sure we'll figure out your issue if we work on  
it systematically.  OK, your OP just said, ..I can't seem to get my  
foreach loops to work..  , but you never said exactly what is the  
problem.  Break the problem down to the smallest thing that you can  
find that is not behaving as you expect it to, and explain  THAT to  
me.  We'll do this step by step.


-John

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread Allen McCabe
I am using the print function to display my html. I cannot get the line
return ( \n ) character to actually push the html onto the next line, it
just gets displayed instead. Should I be using echo?



On Mon, Aug 10, 2009 at 3:41 PM, John Butler
govinda.webdnat...@gmail.comwrote:


 I did this, and got my arrays dumped (on one line). After adding line
 returns, here is a snippet:



 it looks OK.  Note that you can see (copy/paste) that array which you just
 dumped, much better, if you view the source code of the html page.  OR you
 can use pre to make that format persist thru' to what you see without
 viewing the source., Like so:

echo hr /pre\n;
var_dump($theArray);
echo /pre\n;
echo hr /\n;

 My brain is so full of my own work..  and I am newbie compared to most
 lurking here.. but I am sure we'll figure out your issue if we work on it
 systematically.  OK, your OP just said, ..I can't seem to get my foreach
 loops to work..  , but you never said exactly what is the problem.  Break
 the problem down to the smallest thing that you can find that is not
 behaving as you expect it to, and explain  THAT to me.  We'll do this step
 by step.

 -John


 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Embedding foreach loops

2009-08-10 Thread Ben Dunlap
 $shows = array();
  $show_01 = array();
  $show_01['title'] = 'Van Cliburn Gold Medal Winner';
  $show_01['date'] = 'Tues. 10/13/2009';
  $show_01['time'] = '11am';
  $show_01['price'] = 4.00;
  $show_01['soldout'] = 0; //IF THE SHOW SELLS OUT, CHANGE 0 to 1
 (without quotations).
  $shows['show_01'] = $show_01;
[etc.]

If I'm setting up a lot of static data ahead of time like this, I
prefer a slightly simpler syntax (or at least it seems simpler to me):

$shows = array(
'show_01' = array(
'title' = 'Van Cliburn Gold Medal Winner',
'date' = [etc.]
),
'show_02' = array(
'title' = [etc.]
),
[etc.]
);

And sure, you could do all this in a database, or some other sort of
external storage, but unless you're looking at creating a separate UI
for someone other than yourself to input the data, it's probably
simpler all around just to define the data directly in PHP. No reason
you couldn't upgrade to something more sophisticated down the road, if
the customer requires it.

Ben

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Embedding foreach loops

2009-08-10 Thread Daevid Vincent
You're not using the pre and /pre tag most likely then. 

 -Original Message-
 From: Allen McCabe [mailto:allenmcc...@gmail.com] 
 Sent: Monday, August 10, 2009 4:11 PM
 To: John Butler
 Cc: phpList
 Subject: Re: [PHP] Embedding foreach loops
 
 I am using the print function to display my html. I cannot 
 get the line
 return ( \n ) character to actually push the html onto the 
 next line, it
 just gets displayed instead. Should I be using echo?
 
 
 
 On Mon, Aug 10, 2009 at 3:41 PM, John Butler
 govinda.webdnat...@gmail.comwrote:
 
 
  I did this, and got my arrays dumped (on one line). After 
 adding line
  returns, here is a snippet:
 
 
 
  it looks OK.  Note that you can see (copy/paste) that array 
 which you just
  dumped, much better, if you view the source code of the 
 html page.  OR you
  can use pre to make that format persist thru' to what you 
 see without
  viewing the source., Like so:
 
 echo hr /pre\n;
 var_dump($theArray);
 echo /pre\n;
 echo hr /\n;
 
  My brain is so full of my own work..  and I am newbie 
 compared to most
  lurking here.. but I am sure we'll figure out your issue if 
 we work on it
  systematically.  OK, your OP just said, ..I can't seem to 
 get my foreach
  loops to work..  , but you never said exactly what is the 
 problem.  Break
  the problem down to the smallest thing that you can find that is not
  behaving as you expect it to, and explain  THAT to me.  
 We'll do this step
  by step.
 
  -John
 
 
  --
  PHP General Mailing List (http://www.php.net/)
  To unsubscribe, visit: http://www.php.net/unsub.php
 
 
 


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread Ben Dunlap
 I am using the print function to display my html. I cannot get the line
 return ( \n ) character to actually push the html onto the next line, it
 just gets displayed instead. Should I be using echo?

In the PHP code snippet you pasted above, you're using single-quotes
to delimit your literal strings. In-between single-quotes, '\n' is not
converted to a newline character. It's interpeted completely
literally:

http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.single

Also, are you looking to insert a line break into the HTML itself --
just to keep your HTML code clean -- or into the visible page that's
rendered from the HTML? Because newlines don't have any significance
in HTML. You'd need to insert a br / or close a block-level element
to get the effect of a line-break in the visible page.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Embedding foreach loops

2009-08-10 Thread John Butler
I am using the print function to display my html. I cannot get the  
line return ( \n ) character to actually push the html onto the next  
line, it just gets displayed instead. Should I be using echo?



Allen, you off and running again?

echo blah..  \n; //-- this will print  the literal 'blah..  '  and  
then a newline into your HTML *source code*
echo 'blah..  \n'; //-- this will print the literal 'blah..  \n' into  
your HTML *source code*


IIRC print is the same as echo.  That is not your apparent issue.

Say if you are stuck again, and on what exactly.

-John

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach and destroying variables for memory saving

2008-12-10 Thread Carlos Medina

Tim | iHostNZ schrieb:

Hi All,

Just to annoy the hell out of you, another thing that has been on my mind
for a while:

I love the foreach ($ar as $k = $v) { ... } construct and use it all the
time. However, I read somewhere that foreach actually uses a copy of $ar
instead of the array itself by reference. Wouldn't it be much more
usefull/efficient, if foreach would use the array by reference? Then one
could change arrays while iterating over them (without having to use the old
fashioned for ($i=0; $icount($ar); $i++), also this doesnt work for
associative arrays). I know you can do it with while and list somehow, but i
personally find that language construct rather ugly and can never remember
it. Is there another way that any of you use? Please enlighten me.
I just use foreach because its easy, but it might not be the best. However,
it seems to perform good enough for what i've done so far.

Somewhere i also read that one can save a lot of memory by destroying
variables. Is that done with unset, setting it to null or something similar?
So, i take there is no garbage collection in php? I've never actually looked
at the c source code of php. Maybe its time to actually do that. But it
might be easier if someone can answer this from the top of their head.

Thanks for your patience.


Hi Tim,
i can remember me to hear/read that the variables on PHP will be destroy 
 automatically?.


Regards

Carlos

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach and destroying variables for memory saving

2008-12-10 Thread Gal Gur-Arie
Tim | iHostNZ wrote:
 Hi All,
 
 Just to annoy the hell out of you, another thing that has been on my mind
 for a while:
 
 I love the foreach ($ar as $k = $v) { ... } construct and use it all the
 time. However, I read somewhere that foreach actually uses a copy of $ar
 instead of the array itself by reference. Wouldn't it be much more
 usefull/efficient, if foreach would use the array by reference? Then one
 could change arrays while iterating over them (without having to use the old
 fashioned for ($i=0; $icount($ar); $i++), also this doesnt work for
 associative arrays). I know you can do it with while and list somehow, but i
 personally find that language construct rather ugly and can never remember
 it. Is there another way that any of you use? Please enlighten me.
 I just use foreach because its easy, but it might not be the best. However,
 it seems to perform good enough for what i've done so far.
You can use:
$arr = array('abc'='123','ver'=phpversion());
foreach ($arr as $key=$val) {
echo $val.\n;
// Beware! - Changing $val will change it in $arr
}

// or like this:

$arr = array('abc'='123','ver'=phpversion());
reset($arr);
while (list($key, $val) = each($arr)) {
echo $val.\n;
}


 
 Somewhere i also read that one can save a lot of memory by destroying
 variables. Is that done with unset, setting it to null or something similar?
 So, i take there is no garbage collection in php? I've never actually looked
 at the c source code of php. Maybe its time to actually do that. But it
 might be easier if someone can answer this from the top of their head.
 
 Thanks for your patience.
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach questions

2008-01-01 Thread jekillen


On Jan 1, 2008, at 11:59 AM, Martin Jerga wrote:


Hello,
the problem is in this part of code $key - $value
This notation means that you are trying to access property $value on 
the object $key.


Just replace it with $key = $value and you will get the result as 
expected.


Martin J


Thank  you for the response;
I should have known. I don't use this type of loop often enough
to get it straight the first time.
Jeff K


jekillen  wrote / napísal(a):

Hello;
I have this section of code:
 @include('tmp_index.php');
   foreach($index as $key - $value)
  {
   if($input == $key)
 {
  $target_file = $value;
 }
  }
And I am getting this error:
Fatal error: Cannot access empty property in path/confirmation.php 
on line 131

Several questions:
How long can an index be in an associative array? (the indexes I use 
in this array are 32 character hashes)

Can it start with a number (since a hash can start with a number)
Can I use $index as an array name? (I do not remember off hand what 
the reserved key words are)

I am not sure what the empty property is that it is referring to.
Thank you in advance for info;
Jeff K




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach questions

2008-01-01 Thread Martin Jerga

Hello,
the problem is in this part of code $key - $value
This notation means that you are trying to access property $value on the 
object $key.


Just replace it with $key = $value and you will get the result as expected.

Martin J

jekillen  wrote / napísal(a):

Hello;
I have this section of code:

 @include('tmp_index.php');
   foreach($index as $key - $value)
  {
   if($input == $key)
 {
  $target_file = $value;
 }
  }
And I am getting this error:
Fatal error: Cannot access empty property in path/confirmation.php on 
line 131


Several questions:
How long can an index be in an associative array? (the indexes I use in 
this array are 32 character hashes)

Can it start with a number (since a hash can start with a number)
Can I use $index as an array name? (I do not remember off hand what the 
reserved key words are)

I am not sure what the empty property is that it is referring to.
Thank you in advance for info;
Jeff K



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: foreach questions

2008-01-01 Thread Richard Lynch
Hit send too soon.  Sorry!

On Tue, January 1, 2008 2:05 pm, jekillen wrote:
 Several questions:
 How long can an index be in an associative array? (the indexes I
 use
 in this array are 32 character hashes)

As far as I know, it can be as big as your RAM will hold...

 Can it start with a number (since a hash can start with a number)

Yes.

A variable name cannot start with a number.

 Can I use $index as an array name? (I do not remember off hand what
 the reserved key words are)

You can use '$index' if you want, sure.

-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Re: foreach questions

2008-01-01 Thread jekillen


On Jan 1, 2008, at 3:34 PM, Richard Lynch wrote:


Hit send too soon.  Sorry!

On Tue, January 1, 2008 2:05 pm, jekillen wrote:

Several questions:
How long can an index be in an associative array? (the indexes I
use
in this array are 32 character hashes)


As far as I know, it can be as big as your RAM will hold...


Can it start with a number (since a hash can start with a number)


Yes.

A variable name cannot start with a number.


Can I use $index as an array name? (I do not remember off hand what
the reserved key words are)


You can use '$index' if you want, sure.


Thanks for the info;
Jeff K

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-30 Thread Robert Cummings
On Fri, 2007-11-30 at 14:46 -0500, Robert Cummings wrote:

 This is dangerous use of the array functions. A problem occurs when you
 have a value that evaluates to false (such as the first entry in the
 example array :). In fact the only way to ensure you traverse the array
 properly is to use each() since it returns an array except when no more
 entries exist. Also you want to reset() the array before looping
 (normally anyways).
 
 ?php
 
 reset( $data );
 while( ($entry = each( $data )) )
 {
 // ...
 
 if( $errorCondition )
 {
 prev( $data );
 continue;
 }
 
 next( $data );

Newbie bug!! Newbie bug!! each() advances the array pointer so don't do
a next() call :)

Cheers,
Rob.
-- 
...
SwarmBuy.com - http://www.swarmbuy.com

Leveraging the buying power of the masses!
...

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-30 Thread Robert Cummings
On Fri, 2007-11-30 at 09:51 -0800, Jim Lucas wrote:
 Jeffery Fernandez wrote:
  Hi all,
  
  Is it possible to rewind a foreach loop? eg:
  
  
  $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
  
  foreach ($numbers as $index = $value)
  {
  if ($value == 5)
  {
  prev($numbers);
  }
  echo Value: $value . PHP_EOL;
  }
  
  The above doesn't seem to work. In one of my scenarios, when I encounter 
  and 
  error in a foreach loop, I need the ability to rewind the array pointer by 
  one. How can I achieve this?
  
  regards,
  Jeffery
 
 No, you can't rewind the array.  Foreach makes a copy of the array, and works 
 off that copy.
 
 You might need to look into using do...while() instead
 
 Something thing like this should work.
 
 
 ?php
 
 $row = current($your_array);  Gives you the first element in $your_array
 
 do {
 
 ...
 work with your $row...
 determine if their is an error
 ...
 
   if ( $error ) {
   # Watch out for infinite loop
   # maybe have a counter that increments each time it rewinds 
 $your_array
   #and have it stop at 10 loops or something.
   prev($your_array);
   }
 } while( $row = next($your_array) );
 
 ?

This is dangerous use of the array functions. A problem occurs when you
have a value that evaluates to false (such as the first entry in the
example array :). In fact the only way to ensure you traverse the array
properly is to use each() since it returns an array except when no more
entries exist. Also you want to reset() the array before looping
(normally anyways).

?php

reset( $data );
while( ($entry = each( $data )) )
{
// ...

if( $errorCondition )
{
prev( $data );
continue;
}

next( $data );
}

?

Cheers,
Rob.
-- 
...
SwarmBuy.com - http://www.swarmbuy.com

Leveraging the buying power of the masses!
...

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-30 Thread Jim Lucas

Jeffery Fernandez wrote:

Hi all,

Is it possible to rewind a foreach loop? eg:


$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index = $value)
{
if ($value == 5)
{
prev($numbers);
}
echo Value: $value . PHP_EOL;
}

The above doesn't seem to work. In one of my scenarios, when I encounter and 
error in a foreach loop, I need the ability to rewind the array pointer by 
one. How can I achieve this?


regards,
Jeffery


No, you can't rewind the array.  Foreach makes a copy of the array, and works 
off that copy.

You might need to look into using do...while() instead

Something thing like this should work.


?php

$row = current($your_array);  Gives you the first element in $your_array

do {

...
work with your $row...
determine if their is an error
...

if ( $error ) {
# Watch out for infinite loop
# maybe have a counter that increments each time it rewinds 
$your_array
#and have it stop at 10 loops or something.
prev($your_array);
}
} while( $row = next($your_array) );

?


This way, you are working on the only copy of $your_array

--
Jim Lucas

   Some men are born to greatness, some achieve greatness,
   and some have greatness thrust upon them.

Twelfth Night, Act II, Scene V
by William Shakespeare

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-30 Thread Jochem Maas
Jeffery Fernandez wrote:
 Hi all,
 
 Is it possible to rewind a foreach loop? eg:
 
 
 $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
 
 foreach ($numbers as $index = $value)
 {
 if ($value == 5)
 {
 prev($numbers);
 }
 echo Value: $value . PHP_EOL;
 }

this might give you an[other] idea ... note it's
an infinite loop - watch out for those.

do {
foreach (array(0,1,2,3,4,5,6,7,8,9,10) as $k = $v) {
if ($v == 5) continue 2;
echo $v, PHP_EOL;
}
} while (true);

 
 The above doesn't seem to work. In one of my scenarios, when I encounter and 
 error in a foreach loop, I need the ability to rewind the array pointer by 
 one. How can I achieve this?
 
 regards,
 Jeffery

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Rewind foreach loop

2007-11-29 Thread Jeffery Fernandez
Hi all,

Is it possible to rewind a foreach loop? eg:


$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index = $value)
{
if ($value == 5)
{
prev($numbers);
}
echo Value: $value . PHP_EOL;
}

The above doesn't seem to work. In one of my scenarios, when I encounter and 
error in a foreach loop, I need the ability to rewind the array pointer by 
one. How can I achieve this?

regards,
Jeffery
-- 
Internet Vision Technologies
Level 1, 520 Dorset Road
Croydon
Victoria - 3136
Australia
web: http://www.ivt.com.au
phone: +61 3 9723 9399
fax: +61 3 9723 4899

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Jeffery Fernandez
I think the best option for me is to refactorise my code a bit to cater to my 
situation. Thanks all for your help.

Jeffery

On Fri, 30 Nov 2007 02:32:11 pm Jeffery Fernandez wrote:
 On Fri, 30 Nov 2007 02:13:52 pm Chris wrote:
  Jeffery Fernandez wrote:
   On Fri, 30 Nov 2007 02:01:47 pm Chris wrote:
   Jeffery Fernandez wrote:
   Hi all,
  
   Is it possible to rewind a foreach loop? eg:
  
  
   $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
  
   foreach ($numbers as $index = $value)
   {
   if ($value == 5)
   {
   prev($numbers);
   }
   echo Value: $value . PHP_EOL;
   }
  
   The above doesn't seem to work. In one of my scenarios, when I
   encounter and error in a foreach loop, I need the ability to rewind
   the array pointer by one. How can I achieve this?
  
   echo $numbers[$index-1] . PHP_EOL;
  
   That will only give me the value of the previous index. What I want is
   to rewind the array pointer and continue with the loop.
 
  and you're going to be in an endless loop then.. because each time it
  gets rewound, it gets the same key again and rewinds and ...

 No, I am only rewinding if there is an error. Then I have the script
 auto-learning from the error, fix a config file and then want to go back to
 the array pointer to re-execute the process.

  You could do it with a for or while loop probably.

 Thats what I am looking at now.

  What are you trying to achieve? Maybe there's an alternative.

 As mentioned above.

 cheers,
 Jeffery

  --
  Postgresql  php tutorials
  http://www.designmagick.com/

 --
 Internet Vision Technologies
 Level 1, 520 Dorset Road
 Croydon
 Victoria - 3136
 Australia
 web: http://www.ivt.com.au
 phone: +61 3 9723 9399
 fax: +61 3 9723 4899



-- 
Internet Vision Technologies
Level 1, 520 Dorset Road
Croydon
Victoria - 3136
Australia
web: http://www.ivt.com.au
phone: +61 3 9723 9399
fax: +61 3 9723 4899

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Casey

$keys = array_values($array);
for ($i=0; $icount($keys); $i++) {
if ($keys[$i] == 5)
$i -= 2;
}

Untested, but should work.

On Nov 29, 2007, at 7:13 PM, Chris [EMAIL PROTECTED] wrote:


Jeffery Fernandez wrote:

On Fri, 30 Nov 2007 02:01:47 pm Chris wrote:

Jeffery Fernandez wrote:

Hi all,

Is it possible to rewind a foreach loop? eg:


$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index = $value)
{
   if ($value == 5)
   {
   prev($numbers);
   }
   echo Value: $value . PHP_EOL;
}

The above doesn't seem to work. In one of my scenarios, when I  
encounter

and error in a foreach loop, I need the ability to rewind the array
pointer by one. How can I achieve this?

echo $numbers[$index-1] . PHP_EOL;
That will only give me the value of the previous index. What I want  
is to rewind the array pointer and continue with the loop.


and you're going to be in an endless loop then.. because each time  
it gets rewound, it gets the same key again and rewinds and ...


You could do it with a for or while loop probably.

What are you trying to achieve? Maybe there's an alternative.

--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Steve Edberg

At 2:11 PM +1100 11/30/07, Jeffery Fernandez wrote:

On Fri, 30 Nov 2007 02:01:47 pm Chris [EMAIL PROTECTED] wrote:

 Jeffery Fernandez wrote:
  Hi all,
 
  Is it possible to rewind a foreach loop? eg:
 
 
  $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
 
  foreach ($numbers as $index = $value)
  {
  if ($value == 5)
  {
  prev($numbers);
  }

   echo Value: $value . PHP_EOL;

  }
 
  The above doesn't seem to work. In one of my scenarios, when I encounter
  and error in a foreach loop, I need the ability to rewind the array
  pointer by one. How can I achieve this?

 echo $numbers[$index-1] . PHP_EOL;


That will only give me the value of the previous index. What I want is to
rewind the array pointer and continue with the loop.



I would think that if you rewound the array pointer as above, you'd 
simply end up in an infinite loop, as you'd keep hitting the 
condition that triggered the rewind. So I'm assuming you have some 
other test in there and this is just a stripped down example.


If you're using a one-dimensional array, as opposed to a 
multidimensional and/or associative array, you can do (untested):


$Count = count($numbers);

for ($i=0; $i$Count; $i++) {
$value = $numbers[$i];
if ($value == 5  some_other_test()) {
$value = $numbers[--$i];
}
echo Value: $value . PHP_EOL;
}

Wouldn't be much more complex to extend to a multidimensional array 
with an integer index. If you were using an associative array with a 
string index, you'd probably have to do something like


$NotJustNumbers = array('a'='slurm', 'b'='fry', 'c'='leela');
$Keys = array_keys($NotJustNumbers);
$Count = count($Keys);

for ($i=0; $i$Count; $i++) {
$value = $NotJustNumbers[$Keys[$i]];
if ($value == 5  some_other_test()) {
$value = $NotJustNumbers[$Keys[--$i]];
}
echo Value: $value . PHP_EOL;
}


- steve

--
+--- my people are the people of the dessert, ---+
| Steve Edberghttp://pgfsun.ucdavis.edu/ |
| UC Davis Genome Center[EMAIL PROTECTED] |
| Bioinformatics programming/database/sysadmin (530)754-9127 |
+ said t e lawrence, picking up his fork +

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Chris

Jeffery Fernandez wrote:

Hi all,

Is it possible to rewind a foreach loop? eg:


$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index = $value)
{
if ($value == 5)
{
prev($numbers);
}
echo Value: $value . PHP_EOL;
}

The above doesn't seem to work. In one of my scenarios, when I encounter and 
error in a foreach loop, I need the ability to rewind the array pointer by 
one. How can I achieve this?


echo $numbers[$index-1] . PHP_EOL;

Of course that assumes that the value you're looking for isn't the first 
element :)


--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Jeffery Fernandez
On Fri, 30 Nov 2007 02:01:47 pm Chris wrote:
 Jeffery Fernandez wrote:
  Hi all,
 
  Is it possible to rewind a foreach loop? eg:
 
 
  $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
 
  foreach ($numbers as $index = $value)
  {
  if ($value == 5)
  {
  prev($numbers);
  }
  echo Value: $value . PHP_EOL;
  }
 
  The above doesn't seem to work. In one of my scenarios, when I encounter
  and error in a foreach loop, I need the ability to rewind the array
  pointer by one. How can I achieve this?

 echo $numbers[$index-1] . PHP_EOL;

That will only give me the value of the previous index. What I want is to 
rewind the array pointer and continue with the loop.


 Of course that assumes that the value you're looking for isn't the first
 element :)

 --
 Postgresql  php tutorials
 http://www.designmagick.com/



-- 
Internet Vision Technologies
Level 1, 520 Dorset Road
Croydon
Victoria - 3136
Australia
web: http://www.ivt.com.au
phone: +61 3 9723 9399
fax: +61 3 9723 4899

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Chris

Jeffery Fernandez wrote:

On Fri, 30 Nov 2007 02:01:47 pm Chris wrote:

Jeffery Fernandez wrote:

Hi all,

Is it possible to rewind a foreach loop? eg:


$numbers = array(0,1,2,3,4,5,6,7,8,9,10);

foreach ($numbers as $index = $value)
{
if ($value == 5)
{
prev($numbers);
}
echo Value: $value . PHP_EOL;
}

The above doesn't seem to work. In one of my scenarios, when I encounter
and error in a foreach loop, I need the ability to rewind the array
pointer by one. How can I achieve this?

echo $numbers[$index-1] . PHP_EOL;


That will only give me the value of the previous index. What I want is to 
rewind the array pointer and continue with the loop.


and you're going to be in an endless loop then.. because each time it 
gets rewound, it gets the same key again and rewinds and ...


You could do it with a for or while loop probably.

What are you trying to achieve? Maybe there's an alternative.

--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Rewind foreach loop

2007-11-29 Thread Jeffery Fernandez
On Fri, 30 Nov 2007 02:13:52 pm Chris wrote:
 Jeffery Fernandez wrote:
  On Fri, 30 Nov 2007 02:01:47 pm Chris wrote:
  Jeffery Fernandez wrote:
  Hi all,
 
  Is it possible to rewind a foreach loop? eg:
 
 
  $numbers = array(0,1,2,3,4,5,6,7,8,9,10);
 
  foreach ($numbers as $index = $value)
  {
  if ($value == 5)
  {
  prev($numbers);
  }
  echo Value: $value . PHP_EOL;
  }
 
  The above doesn't seem to work. In one of my scenarios, when I
  encounter and error in a foreach loop, I need the ability to rewind the
  array pointer by one. How can I achieve this?
 
  echo $numbers[$index-1] . PHP_EOL;
 
  That will only give me the value of the previous index. What I want is to
  rewind the array pointer and continue with the loop.

 and you're going to be in an endless loop then.. because each time it
 gets rewound, it gets the same key again and rewinds and ...

No, I am only rewinding if there is an error. Then I have the script 
auto-learning from the error, fix a config file and then want to go back to 
the array pointer to re-execute the process.


 You could do it with a for or while loop probably.
Thats what I am looking at now.


 What are you trying to achieve? Maybe there's an alternative.
As mentioned above.

cheers,
Jeffery

 --
 Postgresql  php tutorials
 http://www.designmagick.com/



-- 
Internet Vision Technologies
Level 1, 520 Dorset Road
Croydon
Victoria - 3136
Australia
web: http://www.ivt.com.au
phone: +61 3 9723 9399
fax: +61 3 9723 4899

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] for/foreach speed

2007-08-26 Thread Richard Lynch
On Mon, August 20, 2007 11:50 am, Sascha Braun, CEO @ fit-o-matic wrote:
 could somebody please explain me, what loop construct is
 faster? The for, while or foreach.

If you are doing anything where the speed of for/while/foreach
matters, you shouldn't have done that in PHP in the first place, but
should have put it into a custom PHP extension. :-)


-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] for/foreach speed

2007-08-20 Thread Sascha Braun, CEO @ fit-o-matic
Hi people,

could somebody please explain me, what loop construct is
faster? The for, while or foreach.

I at the moment don't know if there are more.

And thanks to the person who is missusing the list here
for sending trojan horses everywhere.

Since I write to the PHP General list I am receiving round
about 5 E-Mails from random domains, from this list, containing
a Jpeg image with an embeded trojan horse.

Thats really wonderfull. But maybe I should say, that we are
using a nice mailscanner, and as well we are only working on
linux machines.

So better find another way of performing your frauds.

If there are people here in the list, who would like to discuss
how its possible to fight this kind of fraud. I am very open to
that.

Get the hacking tools prepared and lets fight back. I am sure
the police would love to get an inquiry from a hole bunch of
senior developers wanting to see little assholes in jail!

Best Regards,

Sascha Braun

--
BRAUN Networks

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] for/foreach speed

2007-08-20 Thread Robert Cummings
On Mon, 2007-08-20 at 18:50 +0200, Sascha Braun, CEO @ fit-o-matic
wrote:
 Hi people,
 
 could somebody please explain me, what loop construct is
 faster? The for, while or foreach.

I haven't bothered testing but I'd wager $5 that the following is the
fastest loop:

?php

while( 1 )
{
}

?

Depending on bytecode creation though, the following might be just as
fast:

?php

for( ;; )
{
}

?

Cheers,
Rob.
-- 
...
SwarmBuy.com - http://www.swarmbuy.com

Leveraging the buying power of the masses!
...

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] for/foreach speed

2007-08-20 Thread Sascha Braun, CEO @ fit-o-matic
Thank you very much. When we might have time for testing we can
wager :))

Am Montag, den 20.08.2007, 13:21 -0400 schrieb Robert Cummings:
 On Mon, 2007-08-20 at 18:50 +0200, Sascha Braun, CEO @ fit-o-matic
 wrote:
  Hi people,
  
  could somebody please explain me, what loop construct is
  faster? The for, while or foreach.
 
 I haven't bothered testing but I'd wager $5 that the following is the
 fastest loop:
 
 ?php
 
 while( 1 )
 {
 }
 
 ?
 
 Depending on bytecode creation though, the following might be just as
 fast:
 
 ?php
 
 for( ;; )
 {
 }
 
 ?
 
 Cheers,
 Rob.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Nested foreach statement

2006-08-03 Thread Richard Lynch
It will probably work, and you could find out for sure by just trying it.

It might be better to construct a single query using things like:

$company_ids = implode(', ', $_POST['reporton_company']);
$query .=  WHERE company_id IN ($company_ids) ;

This presumes you have already validated the company_ids.

However, if the number of companies, periods, and questions is SMALL,
the difference between one big query and a dozen little queries is
pretty minimal, and if you find the nested loops easier to maintain,
go for it.

On Mon, July 31, 2006 5:02 am, Chris Grigor wrote:
 Have been wondering if this is possible

 Basically I have 3 posted arrays,
 $_POST['reporton_company']  (this can be various company id's. ie
 3,6,7)
 $_POST['report_period'] (this can be various periods but a max of 4
 submitted. ie 3,4,5)
 $_POST['questions_groups'] (this can be various - starting from 1-
 whatever
 (usually a max of 10 or 11). ie 1,2,3,4,5,6,7,8,9,10)

 So the select should work as

 1. for each company listed go through the loop
 2. for each report period listed go through loop for each company
 3. for each questions group go through the loop for each report period
 and
 each company..

 So I came up with this - will it work??


 foreach($_POST['reporton_company'] as $cmp_ind =$arrayd_cmp_id) {
   foreach($_POST['report_period'] as $rep_ind =$arrayd_per_id) {
   foreach($_POST['questions_groups'] as $group_ind =
 $arrayd_group_no) {
   mysql_select_db($database_name, $dname);

   $query_get_list_of_answers = SELECT * FROM answers 
 LEFT JOIN
 (questions,
 period) ON (questions.id=answers.ans_l_question_idAND
 period.per_id=ans_l_period_id) where ans_l_company_id =
 '$arrayd_cmp_id' AND
 per_id = '$arrayd_per_id' AND group_no =  
 '$arrayd_group_no';;

 $get_list_of_answers = mysql_query($query_get_list_of_answers,
 $antiva) or
 die(mysql_error());
 $row_get_list_of_answers = mysql_fetch_assoc($get_list_of_answers);
 $totalRows_get_list_of_answers = mysql_num_rows($get_list_of_answers);
   }

   }
 }

 Anyone suggest an easier way?

 Cheers
 Chris

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Nested foreach statement

2006-07-31 Thread Chris Grigor
Have been wondering if this is possible

Basically I have 3 posted arrays,
$_POST['reporton_company']  (this can be various company id's. ie 3,6,7)
$_POST['report_period'] (this can be various periods but a max of 4
submitted. ie 3,4,5)
$_POST['questions_groups'] (this can be various - starting from 1- whatever
(usually a max of 10 or 11). ie 1,2,3,4,5,6,7,8,9,10)

So the select should work as

1. for each company listed go through the loop
2. for each report period listed go through loop for each company
3. for each questions group go through the loop for each report period and
each company..

So I came up with this - will it work??


foreach($_POST['reporton_company'] as $cmp_ind =$arrayd_cmp_id) {
foreach($_POST['report_period'] as $rep_ind =$arrayd_per_id) {
foreach($_POST['questions_groups'] as $group_ind = 
$arrayd_group_no) {
mysql_select_db($database_name, $dname);

$query_get_list_of_answers = SELECT * FROM answers 
LEFT JOIN (questions,
period) ON (questions.id=answers.ans_l_question_id  AND
period.per_id=ans_l_period_id) where ans_l_company_id = '$arrayd_cmp_id' AND
per_id = '$arrayd_per_id' AND group_no =
'$arrayd_group_no';;

$get_list_of_answers = mysql_query($query_get_list_of_answers, $antiva) or
die(mysql_error());
$row_get_list_of_answers = mysql_fetch_assoc($get_list_of_answers);
$totalRows_get_list_of_answers = mysql_num_rows($get_list_of_answers);
}

}
}

Anyone suggest an easier way?

Cheers
Chris

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Nested foreach statement

2006-07-31 Thread chris smith

foreach($_POST['reporton_company'] as $cmp_ind =$arrayd_cmp_id) {
foreach($_POST['report_period'] as $rep_ind =$arrayd_per_id) {
foreach($_POST['questions_groups'] as $group_ind = 
$arrayd_group_no) {
mysql_select_db($database_name, $dname);


Why do that here? That's going to do it for each element in the
arrays, lots of overhead!

Move that outside the first loop.

I'd probably leave it as it is and make sure your data is what you
expect, ie use mysql_real_escape_string in appropriate places.

You could clean up one loop by doing this:

$query_get_list_of_answers = SELECT * FROM answers LEFT JOIN
(questions, period) ON (questions.id=answers.ans_l_question_id AND
period.per_id=ans_l_period_id) where ans_l_company_id =
'$arrayd_cmp_id' AND per_id = '$arrayd_per_id' AND group_no IN ( .
implode(',', $_POST['questions_groups']) . );

but if I can enter dodgy values in the questions_groups form field,
you're hosed.

--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: foreach / unset

2005-10-29 Thread Bogdan Ribic

Richard Lynch wrote:



Anyway, can you do *this* safely as a DOCUMENTED FEATURE:

foreach($array as $k = $v){
  if (...) unset($array[$k]);
}



Well, somewhere in the said manual it is written that foreach operates 
on a *copy* of the array, so you should be safe unsetting values in the 
original array while iterating through the copy.


--

   Open source PHP code generator for DB operations
   http://sourceforge.net/projects/bfrcg/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP] Re: Foreach problem.

2005-02-09 Thread Jason Barnett
Since you didn't post how you created the array, I went ahead and (ugh!)
did it myself.  This works fine.
?php
$elementsarr = Array ('knr', 'subject', 'title', 'kat', 'pages',
'access', 'dofile', MAX_FILE_SIZE, 'pdf', 'dolink', 'link', 'erstam',
'endless', 'from', 'until', 'openbem', 'history', 'closedbem', 'b',
'br', 'bw', 'bay', 'h', 'hb', 'hh', 'mv', 'n', 'nw', 'rp', 's', 'sa',
'sh', 'sn', 't', 'bund' );
print_r($elementsarr);
foreach ($elementsarr as $k = $v) {
  echo $k = $v\n;
}
?
--
Teach a man to fish...
NEW? | http://www.catb.org/~esr/faqs/smart-questions.html
STFA | http://marc.theaimsgroup.com/?l=php-generalw=2
STFM | http://www.php.net/manual/en/index.php
STFW | http://www.google.com/search?q=php
LAZY |
http://mycroft.mozdev.org/download.html?name=PHPsubmitform=Find+search+plugins


signature.asc
Description: OpenPGP digital signature


Re: [PHP] Nested foreach ?

2004-10-18 Thread Stuart Felenstein
Not working.

 foreach($_SESSION['skills'] as $key = $skill)
 {
$query = INSERT INTO table (skill, sky, sku)
 VALUES ('$skill', 

{$_SESSION['skys'][$key]},{$_SESSION['slus'][$key]});
//run query
 }
The foreach is generating an invalid argument. 
I'm just going to show again what I have set up:

There are five for each of these:
input name=skill[] type=text id=skill[]/td
select name=sky[] id=sky[]
select name=slu[] id=slu[]

Then I post the session variables as:
$_SESSION['skills'] = $_POST['skill'];
$_SESSION['skys'] = $_POST['sky']; 
$_SESSION['slus'] = $_POST['slu'];

It looks like the loop above is using the $skills
array to advance through the other arrays ? 

Stuart

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Nested foreach ?

2004-10-18 Thread Graham Cossey
How about this:

// Doing this makes the code below easier to read
$skills = $_SESSION['skills'];
$skys = $_SESSION['skys'];
$slus = $_SESSION['slus'];

// Set up the fixed part of teh query
$query = INSERT INTO table (skill, sky, sku) VALUES (;

// Loop through each set of form elements
foreach($skills as $key = $skill)
{
   $query .= '$skill','{$skys[$key]}','{$slus[$key]}',;
}
$query = rtrim($query, ','); // Remove any comma from end of $query
$query .= ')';  // Close VALUES (

echo $query;  // What do you get?

// RUN QUERY HERE

Graham

 -Original Message-
 From: Stuart Felenstein [mailto:[EMAIL PROTECTED]
 Sent: 18 October 2004 08:24
 To: John Holmes; [EMAIL PROTECTED]
 Subject: Re: [PHP] Nested foreach ?
 
 
 Not working.
 
  foreach($_SESSION['skills'] as $key = $skill)
  {
 $query = INSERT INTO table (skill, sky, sku)
  VALUES ('$skill', 
 
 {$_SESSION['skys'][$key]},{$_SESSION['slus'][$key]});
 //run query
  }
 The foreach is generating an invalid argument. 
 I'm just going to show again what I have set up:
 
 There are five for each of these:
 input name=skill[] type=text id=skill[]/td
 select name=sky[] id=sky[]
 select name=slu[] id=slu[]
 
 Then I post the session variables as:
 $_SESSION['skills'] = $_POST['skill'];
 $_SESSION['skys'] = $_POST['sky']; 
 $_SESSION['slus'] = $_POST['slu'];
 
 It looks like the loop above is using the $skills
 array to advance through the other arrays ? 
 
 Stuart
 
 -- 
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php
 
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Nested foreach ?

2004-10-18 Thread Stuart Felenstein
Wish I had better news.

Warning: Invalid argument supplied for foreach() in
/home/lurkkcom/public_html/TestMultiTrans2.php on line
90
INSERT INTO LurkProfiles_Skicerts (ProfileID,
SkilCerts, NumYear, Lused) VALUES ()


line 90: foreach($skills as $key = $skill)

To confirm : 

I changed to this:
 // Doing this makes the code below easier to read
 $skills = $_SESSION['skills'];
 $skys = $_SESSION['skys'];
 $slus = $_SESSION['slus'];

From this : 
I changed the $_SESSION['skills'] = $_POST['skill']; 
$_SESSION['skys'] = $_POST['sky']; 
$_SESSION['slus'] = $_POST['slu'];

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Nested foreach ?

2004-10-18 Thread Graham Cossey
These lines store the FORM's posted values (arrays)
into your SESSION:
$_SESSION['skills'] = $_POST['skill']; 
$_SESSION['skys'] = $_POST['sky']; 
$_SESSION['slus'] = $_POST['slu'];

These lines get your SESSION variables (arrays) and
put them into 'local' script array variables.
If you are doing these then you MUST have done the above
in the previous script.
$skills = $_SESSION['skills'];
$skys = $_SESSION['skys'];
$slus = $_SESSION['slus'];

If you are doing it all in one script just use:
$skills = $_POST['skills'];
$skys = $_POST['skys'];
$slus = $_POST['slus'];

Make sense?
If not, may I suggest you do a bit of reading on
PHP and form processing before proceeding. 
I have found the PHP manual extremely useful. 
With it (and some googling) I have gone from zero 
PHP knowledge 10 months ago to being able to 
develop and maintain an entire PHP/MySQL based
web application subscribed to by several clients. 


HTH
Graham

 -Original Message-
 From: Stuart Felenstein [mailto:[EMAIL PROTECTED]
 Sent: 18 October 2004 09:37
 To: Graham Cossey; [EMAIL PROTECTED]
 Subject: RE: [PHP] Nested foreach ?
 
 
 Wish I had better news.
 
 Warning: Invalid argument supplied for foreach() in
 /home/lurkkcom/public_html/TestMultiTrans2.php on line
 90
 INSERT INTO LurkProfiles_Skicerts (ProfileID,
 SkilCerts, NumYear, Lused) VALUES ()
 
 
 line 90: foreach($skills as $key = $skill)
 
 To confirm : 
 
 I changed to this:
  // Doing this makes the code below easier to read
  $skills = $_SESSION['skills'];
  $skys = $_SESSION['skys'];
  $slus = $_SESSION['slus'];
 
 From this : 
 I changed the $_SESSION['skills'] = $_POST['skill']; 
 $_SESSION['skys'] = $_POST['sky']; 
 $_SESSION['slus'] = $_POST['slu'];
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



  1   2   >