Re: [PHP] array key's: which is correct?

2010-06-08 Thread Robert Cummings

Tanel Tammik wrote:

Hi,

which one is correct or better?

$array[3] = '';
or
$array['3'] = '';

$i = 7;

$array[$i] = '';
or
$array[$i] = '';


Sometimes it is good to illustrate the correct answer:

?php

$array = array
(
'1' = '1',
'2' = '2',
'three' = 'three',
'4.0'   = '4.0',
5.0 = 5.0,
);

var_dump( array_keys( $array ) );

?

The answer is surprising (well, not really :) and certainly advocates 
against making literal strings of integers or manually converting a 
string integer to a real integer or using floating point keys.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

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



Re: [PHP] array key's: which is correct?

2010-06-08 Thread Ashley Sheridan
On Tue, 2010-06-08 at 09:38 -0400, Robert Cummings wrote:

 Tanel Tammik wrote:
  Hi,
  
  which one is correct or better?
  
  $array[3] = '';
  or
  $array['3'] = '';
  
  $i = 7;
  
  $array[$i] = '';
  or
  $array[$i] = '';
 
 Sometimes it is good to illustrate the correct answer:
 
 ?php
 
 $array = array
 (
  '1' = '1',
  '2' = '2',
  'three' = 'three',
  '4.0'   = '4.0',
  5.0 = 5.0,
 );
 
 var_dump( array_keys( $array ) );
 
 ?
 
 The answer is surprising (well, not really :) and certainly advocates 
 against making literal strings of integers or manually converting a 
 string integer to a real integer or using floating point keys.
 
 Cheers,
 Rob.
 -- 
 E-Mail Disclaimer: Information contained in this message and any
 attached documents is considered confidential and legally protected.
 This message is intended solely for the addressee(s). Disclosure,
 copying, and distribution are prohibited unless authorized.
 


Yeah, I found that out the hard way when I was trying to make an array
of Gantt tasks, and realised that all my nice task numbers were changed!

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




Re: [PHP] array key's: which is correct?

2010-06-08 Thread Paul M Foster
On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:

 Tanel Tammik wrote:
 Hi,

 which one is correct or better?

 $array[3] = '';
 or
 $array['3'] = '';

 $i = 7;

 $array[$i] = '';
 or
 $array[$i] = '';

 Sometimes it is good to illustrate the correct answer:

 ?php

 $array = array
 (
 '1' = '1',
 '2' = '2',
 'three' = 'three',
 '4.0'   = '4.0',
 5.0 = 5.0,
 );

 var_dump( array_keys( $array ) );

 ?

 The answer is surprising (well, not really :) and certainly advocates
 against making literal strings of integers or manually converting a
 string integer to a real integer or using floating point keys.

Curse you, Rob Cummings! ;-}

I was stunned at the results of this. I assumed that integers cast as
strings would remain strings as indexes. Not so. And then float indexes
cast to ints. Argh!

My advice to the original poster was slightly incorrect. But I would
still encourage you to avoid enclosing variables in double-quotes
unnecessarily. (And integers in single-quotes for that matter.)

Paul

-- 
Paul M. Foster

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



Re: [PHP] array key's: which is correct?

2010-06-08 Thread Ashley Sheridan
On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:

 On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
 
  Tanel Tammik wrote:
  Hi,
 
  which one is correct or better?
 
  $array[3] = '';
  or
  $array['3'] = '';
 
  $i = 7;
 
  $array[$i] = '';
  or
  $array[$i] = '';
 
  Sometimes it is good to illustrate the correct answer:
 
  ?php
 
  $array = array
  (
  '1' = '1',
  '2' = '2',
  'three' = 'three',
  '4.0'   = '4.0',
  5.0 = 5.0,
  );
 
  var_dump( array_keys( $array ) );
 
  ?
 
  The answer is surprising (well, not really :) and certainly advocates
  against making literal strings of integers or manually converting a
  string integer to a real integer or using floating point keys.
 
 Curse you, Rob Cummings! ;-}
 
 I was stunned at the results of this. I assumed that integers cast as
 strings would remain strings as indexes. Not so. And then float indexes
 cast to ints. Argh!
 
 My advice to the original poster was slightly incorrect. But I would
 still encourage you to avoid enclosing variables in double-quotes
 unnecessarily. (And integers in single-quotes for that matter.)
 
 Paul
 
 -- 
 Paul M. Foster
 


The obvious way around this would be to include some sort of character
in the index that can't be cast to an integer, so instead of $array[1.0]
which would equate to $array[1] maybe add an underscore to make it
$array['_1.0']. It's not the prettiest of solutions, but it does mean
that indexes are kept as you intended, and you need only strip out the
first character, although I imagine a lot of string manipulation on a
large array would decrease performance.

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




Re: [PHP] array key's: which is correct?

2010-06-08 Thread Peter Lind
On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
 On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:

 On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:

  Tanel Tammik wrote:
  Hi,
 
  which one is correct or better?
 
  $array[3] = '';
  or
  $array['3'] = '';
 
  $i = 7;
 
  $array[$i] = '';
  or
  $array[$i] = '';
 
  Sometimes it is good to illustrate the correct answer:
 
  ?php
 
  $array = array
  (
      '1'     = '1',
      '2'     = '2',
      'three' = 'three',
      '4.0'   = '4.0',
      5.0     = 5.0,
  );
 
  var_dump( array_keys( $array ) );
 
  ?
 
  The answer is surprising (well, not really :) and certainly advocates
  against making literal strings of integers or manually converting a
  string integer to a real integer or using floating point keys.

 Curse you, Rob Cummings! ;-}

 I was stunned at the results of this. I assumed that integers cast as
 strings would remain strings as indexes. Not so. And then float indexes
 cast to ints. Argh!

 My advice to the original poster was slightly incorrect. But I would
 still encourage you to avoid enclosing variables in double-quotes
 unnecessarily. (And integers in single-quotes for that matter.)

 Paul

 --
 Paul M. Foster



 The obvious way around this would be to include some sort of character
 in the index that can't be cast to an integer, so instead of $array[1.0]
 which would equate to $array[1] maybe add an underscore to make it
 $array['_1.0']. It's not the prettiest of solutions, but it does mean
 that indexes are kept as you intended, and you need only strip out the
 first character, although I imagine a lot of string manipulation on a
 large array would decrease performance.

Floats in quotes are not cast to int when used as array keys. Just an FYI :)

Regards
Peter

-- 
hype
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
BeWelcome/Couchsurfing: Fake51
Twitter: http://twitter.com/kafe15
/hype

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



Re: [PHP] array key's: which is correct?

2010-06-08 Thread Ashley Sheridan
On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote:

 On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
  On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:
 
  On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
 
   Tanel Tammik wrote:
   Hi,
  
   which one is correct or better?
  
   $array[3] = '';
   or
   $array['3'] = '';
  
   $i = 7;
  
   $array[$i] = '';
   or
   $array[$i] = '';
  
   Sometimes it is good to illustrate the correct answer:
  
   ?php
  
   $array = array
   (
   '1' = '1',
   '2' = '2',
   'three' = 'three',
   '4.0'   = '4.0',
   5.0 = 5.0,
   );
  
   var_dump( array_keys( $array ) );
  
   ?
  
   The answer is surprising (well, not really :) and certainly advocates
   against making literal strings of integers or manually converting a
   string integer to a real integer or using floating point keys.
 
  Curse you, Rob Cummings! ;-}
 
  I was stunned at the results of this. I assumed that integers cast as
  strings would remain strings as indexes. Not so. And then float indexes
  cast to ints. Argh!
 
  My advice to the original poster was slightly incorrect. But I would
  still encourage you to avoid enclosing variables in double-quotes
  unnecessarily. (And integers in single-quotes for that matter.)
 
  Paul
 
  --
  Paul M. Foster
 
 
 
  The obvious way around this would be to include some sort of character
  in the index that can't be cast to an integer, so instead of $array[1.0]
  which would equate to $array[1] maybe add an underscore to make it
  $array['_1.0']. It's not the prettiest of solutions, but it does mean
  that indexes are kept as you intended, and you need only strip out the
  first character, although I imagine a lot of string manipulation on a
  large array would decrease performance.
 
 Floats in quotes are not cast to int when used as array keys. Just an FYI :)
 
 Regards
 Peter
 


They are. Go look at Robs earlier example. Even building upon that to
make a float value where it doesn't equate to an integer, it is still
cast as an integer unless it's inside a string:

$array = array
(
 '1' = '1',
 '2' = '2',
 'three' = 'three',
 '4.0'   = '4.0',
 5.0 = 5.0,
 6.5= 6.5,
);

var_dump( array_keys( $array ) );

That's Robs code, but I added in the last element to show how a float
index is converted to an integer. Putting the float value inside a
string solves the issue.

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




Re: [PHP] array key's: which is correct?

2010-06-08 Thread Peter Lind
On 8 June 2010 16:53, Ashley Sheridan a...@ashleysheridan.co.uk wrote:

 On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote:

 On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
  On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:
 
  On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
 
   Tanel Tammik wrote:
   Hi,
  
   which one is correct or better?
  
   $array[3] = '';
   or
   $array['3'] = '';
  
   $i = 7;
  
   $array[$i] = '';
   or
   $array[$i] = '';
  
   Sometimes it is good to illustrate the correct answer:
  
   ?php
  
   $array = array
   (
       '1'     = '1',
       '2'     = '2',
       'three' = 'three',
       '4.0'   = '4.0',
       5.0     = 5.0,
   );
  
   var_dump( array_keys( $array ) );
  
   ?
  
   The answer is surprising (well, not really :) and certainly advocates
   against making literal strings of integers or manually converting a
   string integer to a real integer or using floating point keys.
 
  Curse you, Rob Cummings! ;-}
 
  I was stunned at the results of this. I assumed that integers cast as
  strings would remain strings as indexes. Not so. And then float indexes
  cast to ints. Argh!
 
  My advice to the original poster was slightly incorrect. But I would
  still encourage you to avoid enclosing variables in double-quotes
  unnecessarily. (And integers in single-quotes for that matter.)
 
  Paul
 
  --
  Paul M. Foster
 
 
 
  The obvious way around this would be to include some sort of character
  in the index that can't be cast to an integer, so instead of $array[1.0]
  which would equate to $array[1] maybe add an underscore to make it
  $array['_1.0']. It's not the prettiest of solutions, but it does mean
  that indexes are kept as you intended, and you need only strip out the
  first character, although I imagine a lot of string manipulation on a
  large array would decrease performance.

 Floats in quotes are not cast to int when used as array keys. Just an FYI :)

 Regards
 Peter


 They are. Go look at Robs earlier example. Even building upon that to make a 
 float value where it doesn't equate to an integer, it is still cast as an 
 integer unless it's inside a string:

 $array = array
 (
  '1' = '1',
  '2' = '2',
  'three' = 'three',
  '4.0'   = '4.0',
  5.0 = 5.0,
  6.5 = 6.5,
 );

 var_dump( array_keys( $array ) );

 That's Robs code, but I added in the last element to show how a float index 
 is converted to an integer. Putting the float value inside a string solves 
 the issue.


Did you read what I wrote?

 ***Floats in quotes*** are not cast to int when used as array keys. Just an 
 FYI :)

I tested Robs example, that's how I know that floats in quotes are not
converted to ints, whether or not you use '4.0' or '6.5'

Regards
Peter

--
hype
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
BeWelcome/Couchsurfing: Fake51
Twitter: http://twitter.com/kafe15
/hype

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



Re: [PHP] array key's: which is correct?

2010-06-08 Thread Ashley Sheridan
On Tue, 2010-06-08 at 17:11 +0200, Peter Lind wrote:

 On 8 June 2010 16:53, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
 
  On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote:
 
  On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
   On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:
  
   On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
  
Tanel Tammik wrote:
Hi,
   
which one is correct or better?
   
$array[3] = '';
or
$array['3'] = '';
   
$i = 7;
   
$array[$i] = '';
or
$array[$i] = '';
   
Sometimes it is good to illustrate the correct answer:
   
?php
   
$array = array
(
'1' = '1',
'2' = '2',
'three' = 'three',
'4.0'   = '4.0',
5.0 = 5.0,
);
   
var_dump( array_keys( $array ) );
   
?
   
The answer is surprising (well, not really :) and certainly advocates
against making literal strings of integers or manually converting a
string integer to a real integer or using floating point keys.
  
   Curse you, Rob Cummings! ;-}
  
   I was stunned at the results of this. I assumed that integers cast as
   strings would remain strings as indexes. Not so. And then float indexes
   cast to ints. Argh!
  
   My advice to the original poster was slightly incorrect. But I would
   still encourage you to avoid enclosing variables in double-quotes
   unnecessarily. (And integers in single-quotes for that matter.)
  
   Paul
  
   --
   Paul M. Foster
  
  
  
   The obvious way around this would be to include some sort of character
   in the index that can't be cast to an integer, so instead of $array[1.0]
   which would equate to $array[1] maybe add an underscore to make it
   $array['_1.0']. It's not the prettiest of solutions, but it does mean
   that indexes are kept as you intended, and you need only strip out the
   first character, although I imagine a lot of string manipulation on a
   large array would decrease performance.
 
  Floats in quotes are not cast to int when used as array keys. Just an FYI :)
 
  Regards
  Peter
 
 
  They are. Go look at Robs earlier example. Even building upon that to make 
  a float value where it doesn't equate to an integer, it is still cast as an 
  integer unless it's inside a string:
 
  $array = array
  (
   '1' = '1',
   '2' = '2',
   'three' = 'three',
   '4.0'   = '4.0',
   5.0 = 5.0,
   6.5 = 6.5,
  );
 
  var_dump( array_keys( $array ) );
 
  That's Robs code, but I added in the last element to show how a float index 
  is converted to an integer. Putting the float value inside a string solves 
  the issue.
 
 
 Did you read what I wrote?
 
  ***Floats in quotes*** are not cast to int when used as array keys. Just an 
  FYI :)
 
 I tested Robs example, that's how I know that floats in quotes are not
 converted to ints, whether or not you use '4.0' or '6.5'
 
 Regards
 Peter
 
 --
 hype
 WWW: http://plphp.dk / http://plind.dk
 LinkedIn: http://www.linkedin.com/in/plind
 BeWelcome/Couchsurfing: Fake51
 Twitter: http://twitter.com/kafe15
 /hype


Sorry, my bad, I misread your email, you were right!

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




Re: [PHP] array key's: which is correct?

2010-06-08 Thread Paul M Foster
On Tue, Jun 08, 2010 at 04:44:53PM +0200, Peter Lind wrote:

 On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:
  On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:
 
  On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
 
   Tanel Tammik wrote:
   Hi,
  
   which one is correct or better?
  
   $array[3] = '';
   or
   $array['3'] = '';
  
   $i = 7;
  
   $array[$i] = '';
   or
   $array[$i] = '';
  
   Sometimes it is good to illustrate the correct answer:
  
   ?php
  
   $array = array
   (
       '1'     = '1',
       '2'     = '2',
       'three' = 'three',
       '4.0'   = '4.0',
       5.0     = 5.0,
   );
  
   var_dump( array_keys( $array ) );
  
   ?
  
   The answer is surprising (well, not really :) and certainly advocates
   against making literal strings of integers or manually converting a
   string integer to a real integer or using floating point keys.
 
  Curse you, Rob Cummings! ;-}
 
  I was stunned at the results of this. I assumed that integers cast as
  strings would remain strings as indexes. Not so. And then float indexes
  cast to ints. Argh!
 
  My advice to the original poster was slightly incorrect. But I would
  still encourage you to avoid enclosing variables in double-quotes
  unnecessarily. (And integers in single-quotes for that matter.)
 
  Paul
 
  --
  Paul M. Foster
 
 
 
  The obvious way around this would be to include some sort of character
  in the index that can't be cast to an integer, so instead of $array[1.0]
  which would equate to $array[1] maybe add an underscore to make it
  $array['_1.0']. It's not the prettiest of solutions, but it does mean
  that indexes are kept as you intended, and you need only strip out the
  first character, although I imagine a lot of string manipulation on a
  large array would decrease performance.
 
 Floats in quotes are not cast to int when used as array keys. Just an FYI :)

Umm, yes, you are correct. I pasted Rob's code into a test file, added
some other print_r()s and such, just to look at the whole issue. I'm
*still* examining the results, trying to wrap my wits around why things
are done this way.

Paul

-- 
Paul M. Foster

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



Re: [PHP] array key's: which is correct?

2010-06-08 Thread Robert Cummings

Paul M Foster wrote:

On Tue, Jun 08, 2010 at 04:44:53PM +0200, Peter Lind wrote:


On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote:

On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:


On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:


Tanel Tammik wrote:

Hi,

which one is correct or better?

$array[3] = '';
or
$array['3'] = '';

$i = 7;

$array[$i] = '';
or
$array[$i] = '';

Sometimes it is good to illustrate the correct answer:

?php

$array = array
(
'1' = '1',
'2' = '2',
'three' = 'three',
'4.0'   = '4.0',
5.0 = 5.0,
);

var_dump( array_keys( $array ) );

?

The answer is surprising (well, not really :) and certainly advocates
against making literal strings of integers or manually converting a
string integer to a real integer or using floating point keys.

Curse you, Rob Cummings! ;-}

I was stunned at the results of this. I assumed that integers cast as
strings would remain strings as indexes. Not so. And then float indexes
cast to ints. Argh!

My advice to the original poster was slightly incorrect. But I would
still encourage you to avoid enclosing variables in double-quotes
unnecessarily. (And integers in single-quotes for that matter.)

Paul

--
Paul M. Foster



The obvious way around this would be to include some sort of character
in the index that can't be cast to an integer, so instead of $array[1.0]
which would equate to $array[1] maybe add an underscore to make it
$array['_1.0']. It's not the prettiest of solutions, but it does mean
that indexes are kept as you intended, and you need only strip out the
first character, although I imagine a lot of string manipulation on a
large array would decrease performance.

Floats in quotes are not cast to int when used as array keys. Just an FYI :)


Umm, yes, you are correct. I pasted Rob's code into a test file, added
some other print_r()s and such, just to look at the whole issue. I'm
*still* examining the results, trying to wrap my wits around why things
are done this way.


If I were to hazard a guess as to the why of the current 
functionality, I would say converting an integer string to a real i nt 
is optimal with respect to both memory and processing when trying to 
find values by key. As for floating points... Due to the inability to 
accurately represent some floating point numbers in binary, one would 
often not get what one expects even when converting to a string. So 
maybe integer was chosen since it was more optimal than a string.


Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

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



[PHP] Array group and sum values.

2010-05-11 Thread Paul Halliday
I have this:

while ($row = mysql_fetch_array($theData[0])) {

$col1[] = $row[0];
$col2[] = lookup($row[1]); // this goes off and gets the country name.

I then loop through col1 and col2 to produce something like this:

52  ARMENIA
215 CANADA
57  CANADA
261 COLOMBIA
53  EGYPT
62  INDIA
50  INDIA

Is there a way I can group these?

Thanks!

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



Re: [PHP] Array group and sum values.

2010-05-11 Thread Jim Lucas
Paul Halliday wrote:
 I have this:
 
 while ($row = mysql_fetch_array($theData[0])) {
 
 $col1[] = $row[0];
 $col2[] = lookup($row[1]); // this goes off and gets the country name.
 
 I then loop through col1 and col2 to produce something like this:
 
 52ARMENIA
 215   CANADA
 57CANADA
 261   COLOMBIA
 53EGYPT
 62INDIA
 50INDIA
 
 Is there a way I can group these?
 
 Thanks!
 

Group them??

How about this

while ($row = mysql_fetch_array($theData[0])) {

$col1[lookup($row[1])][] = $row[0];

which, using the data you showed, will give you this


Array
(
[ARMENIA] = Array
(
[0] = 52
)

[CANADA] = Array
(
[0] = 215
[1] = 57
)

[COLOMBIA] = Array
(
[0] = 261
)

[EGYPT] = Array
(
[0] = 53
)

[INDIA] = Array
(
[0] = 62
[1] = 50
)

)

-- 
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] Array group and sum values.

2010-05-11 Thread Paul Halliday
On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 I have this:

 while ($row = mysql_fetch_array($theData[0])) {

     $col1[] = $row[0];
     $col2[] = lookup($row[1]); // this goes off and gets the country name.

 I then loop through col1 and col2 to produce something like this:

 52    ARMENIA
 215   CANADA
 57    CANADA
 261   COLOMBIA
 53    EGYPT
 62    INDIA
 50    INDIA

 Is there a way I can group these?

 Thanks!


 Group them??

 How about this

 while ($row = mysql_fetch_array($theData[0])) {

    $col1[lookup($row[1])][] = $row[0];

 which, using the data you showed, will give you this


 Array
 (
    [ARMENIA] = Array
        (
            [0] = 52
        )

    [CANADA] = Array
        (
            [0] = 215
            [1] = 57
        )

    [COLOMBIA] = Array
        (
            [0] = 261
        )

    [EGYPT] = Array
        (
            [0] = 53
        )

    [INDIA] = Array
        (
            [0] = 62
            [1] = 50
        )

 )

 --
 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


I was actually hoping to have them arranged like:

$col1[0] = INDIA
$col2[0] = 112
$col1[1] = CANADA
$col2[1] = 272
...

Thanks.

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



Re: [PHP] Array group and sum values.

2010-05-11 Thread Jim Lucas
Paul Halliday wrote:
 On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 I have this:

 while ($row = mysql_fetch_array($theData[0])) {

 $col1[] = $row[0];
 $col2[] = lookup($row[1]); // this goes off and gets the country name.

 I then loop through col1 and col2 to produce something like this:

 52ARMENIA
 215   CANADA
 57CANADA
 261   COLOMBIA
 53EGYPT
 62INDIA
 50INDIA

 Is there a way I can group these?

 Thanks!

 Group them??

 How about this

 while ($row = mysql_fetch_array($theData[0])) {

$col1[lookup($row[1])][] = $row[0];

 which, using the data you showed, will give you this


 Array
 (
[ARMENIA] = Array
(
[0] = 52
)

[CANADA] = Array
(
[0] = 215
[1] = 57
)

[COLOMBIA] = Array
(
[0] = 261
)

[EGYPT] = Array
(
[0] = 53
)

[INDIA] = Array
(
[0] = 62
[1] = 50
)

 )

 --
 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

 
 I was actually hoping to have them arranged like:
 
 $col1[0] = INDIA
 $col2[0] = 112
 $col1[1] = CANADA
 $col2[1] = 272
 ...
 
 Thanks.
 

Well, then take what I gave you and do this:

$group[lookup($row[1])][] = $row[0];

foreach ( $group AS $x = $y )
{
$col1[] = $x;
$col2[] = array_sum($y);
}


In the end you will end up with this

plaintext?php

$data = array(
array(52,   'ARMENIA'),
array(215,  'CANADA'),
array(57,   'CANADA'),
array(261,  'COLOMBIA'),
array(53,   'EGYPT'),
array(62,   'INDIA'),
array(50,   'INDIA'),
);

foreach ( $data AS $row )
{
$group[$row[1]][] = $row[0];
}

print_r($group);

foreach ( $group AS $x = $y )
{
$col1[] = $x;
$col2[] = array_sum($y);
}

print_r($col1);
print_r($col2);









-- 
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] Array group and sum values.

2010-05-11 Thread Paul Halliday
On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 I have this:

 while ($row = mysql_fetch_array($theData[0])) {

     $col1[] = $row[0];
     $col2[] = lookup($row[1]); // this goes off and gets the country name.

 I then loop through col1 and col2 to produce something like this:

 52    ARMENIA
 215   CANADA
 57    CANADA
 261   COLOMBIA
 53    EGYPT
 62    INDIA
 50    INDIA

 Is there a way I can group these?

 Thanks!



 Group them??

 How about this

 while ($row = mysql_fetch_array($theData[0])) {

    $col1[lookup($row[1])][] = $row[0];

 which, using the data you showed, will give you this


 Array
 (
    [ARMENIA] = Array
        (
            [0] = 52
        )

    [CANADA] = Array
        (
            [0] = 215
            [1] = 57
        )

    [COLOMBIA] = Array
        (
            [0] = 261
        )

    [EGYPT] = Array
        (
            [0] = 53
        )

    [INDIA] = Array
        (
            [0] = 62
            [1] = 50
        )

 )

 --
 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


 I was actually hoping to have them arranged like:

 $col1[0] = INDIA
 $col2[0] = 112
 $col1[1] = CANADA
 $col2[1] = 272
 ...

 Thanks.


 Well, then take what I gave you and do this:

 $group[lookup($row[1])][] = $row[0];

 foreach ( $group AS $x = $y )
 {
        $col1[] = $x;
        $col2[] = array_sum($y);
 }


 In the end you will end up with this

 plaintext?php

 $data = array(
                array(52,       'ARMENIA'),
                array(215,      'CANADA'),
                array(57,       'CANADA'),
                array(261,      'COLOMBIA'),
                array(53,       'EGYPT'),
                array(62,       'INDIA'),
                array(50,       'INDIA'),
                );

 foreach ( $data AS $row )
 {
        $group[$row[1]][] = $row[0];
 }

 print_r($group);

 foreach ( $group AS $x = $y )
 {
        $col1[] = $x;
        $col2[] = array_sum($y);
 }

 print_r($col1);
 print_r($col2);




Perfect! and a lot simpler than I thought.

Thanks.

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



Re: [PHP] Array group and sum values.

2010-05-11 Thread Shawn McKenzie
On 05/11/2010 02:17 PM, Paul Halliday wrote:
 On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 I have this:

 while ($row = mysql_fetch_array($theData[0])) {

 $col1[] = $row[0];
 $col2[] = lookup($row[1]); // this goes off and gets the country name.

 I then loop through col1 and col2 to produce something like this:

 52ARMENIA
 215   CANADA
 57CANADA
 261   COLOMBIA
 53EGYPT
 62INDIA
 50INDIA

 Is there a way I can group these?

 Thanks!
 
 

 Group them??

 How about this

 while ($row = mysql_fetch_array($theData[0])) {

$col1[lookup($row[1])][] = $row[0];

 which, using the data you showed, will give you this


 Array
 (
[ARMENIA] = Array
(
[0] = 52
)

[CANADA] = Array
(
[0] = 215
[1] = 57
)

[COLOMBIA] = Array
(
[0] = 261
)

[EGYPT] = Array
(
[0] = 53
)

[INDIA] = Array
(
[0] = 62
[1] = 50
)

 )

 --
 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


 I was actually hoping to have them arranged like:

 $col1[0] = INDIA
 $col2[0] = 112
 $col1[1] = CANADA
 $col2[1] = 272
 ...

 Thanks.


I would probably do this:

$col1 = $col2 = array();

while ($row = mysql_fetch_array($theData[0])) {
$country = lookup($row[1]);

if(($found = array_search($country, $col1)) !== false) {
$col2[$found] += $row[0];
} else {
$col1[] = $country;
$col2[] = $row[0];
}
}

-- 
Thanks!
-Shawn
http://www.spidean.com

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



Re: [PHP] Array group and sum values.

2010-05-11 Thread Shawn McKenzie
On 05/11/2010 04:09 PM, Shawn McKenzie wrote:
 On 05/11/2010 02:17 PM, Paul Halliday wrote:
 On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote:
 Paul Halliday wrote:
 I have this:

 while ($row = mysql_fetch_array($theData[0])) {

 $col1[] = $row[0];
 $col2[] = lookup($row[1]); // this goes off and gets the country 
 name.

 I then loop through col1 and col2 to produce something like this:

 52ARMENIA
 215   CANADA
 57CANADA
 261   COLOMBIA
 53EGYPT
 62INDIA
 50INDIA

 Is there a way I can group these?

 Thanks!



 Group them??

 How about this

 while ($row = mysql_fetch_array($theData[0])) {

$col1[lookup($row[1])][] = $row[0];

 which, using the data you showed, will give you this


 Array
 (
[ARMENIA] = Array
(
[0] = 52
)

[CANADA] = Array
(
[0] = 215
[1] = 57
)

[COLOMBIA] = Array
(
[0] = 261
)

[EGYPT] = Array
(
[0] = 53
)

[INDIA] = Array
(
[0] = 62
[1] = 50
)

 )

 --
 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


 I was actually hoping to have them arranged like:

 $col1[0] = INDIA
 $col2[0] = 112
 $col1[1] = CANADA
 $col2[1] = 272
 ...

 Thanks.

 
 I would probably do this:
 
 $col1 = $col2 = array();
 
 while ($row = mysql_fetch_array($theData[0])) {
   $country = lookup($row[1]);
 
   if(($found = array_search($country, $col1)) !== false) {
   $col2[$found] += $row[0];
   } else {
   $col1[] = $country;
   $col2[] = $row[0];
   }
 }
 

Although I myself would prefer it to be in this format:

$result = array();

foreach($rows as $row) {
$country = lookup($row[1]);

if(isset($result[$country])) {
$result[$country] += $row[0];
} else {
$result[$country] = $row[0];
}
}

Which would give:

array
(
   INDIA = 112
   CANADA = 272
   //etc...
)

Then to use, just:

foreach($result as $country = $value) {
echo $country . ' ' . $value;  // or whatever
}

-- 
Thanks!
-Shawn
http://www.spidean.com

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



[PHP] Array to csv or excel in php

2010-04-19 Thread Manolis Vlachakis
hallo there everyone..
i got an array from my database
Help with Code 
Tagshttp://www.daniweb.com/forums/misc-explaincode.html?TB_iframe=trueheight=400width=680
*PHP Syntax* (Toggle Plain Texthttp://www.daniweb.com/forums/post1194347.html#
)


   1. $save=split([|;],$listOfItems);


and what i want i s after making some changes to the attributes on the array
above to export them on an csv or excel format
but directly as a message to the browser ..
i dont want it to be saved on the server ...
what i cant understand from the examples i found on the net ..
is how to handle the files and which are created cause
i just have the array in a php file nothing more...


another thing i have in mind is to export from the ldap server the files
directly but seems to me as the wrong way to do it

thanks


Re: [PHP] Array to csv or excel in php

2010-04-19 Thread Andrew Ballard
On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis
vlachakis.mano...@gmail.com wrote:
 hallo there everyone..
 i got an array from my database
 Help with Code 
 Tagshttp://www.daniweb.com/forums/misc-explaincode.html?TB_iframe=trueheight=400width=680
 *PHP Syntax* (Toggle Plain 
 Texthttp://www.daniweb.com/forums/post1194347.html#
 )


   1. $save=split([|;],$listOfItems);


 and what i want i s after making some changes to the attributes on the array
 above to export them on an csv or excel format
 but directly as a message to the browser ..
 i dont want it to be saved on the server ...
 what i cant understand from the examples i found on the net ..
 is how to handle the files and which are created cause
 i just have the array in a php file nothing more...


 another thing i have in mind is to export from the ldap server the files
 directly but seems to me as the wrong way to do it

 thanks


Often when outputting csv, I usually do something like this:

?php

$fp = fopen('php://output', 'w') or die('Could not open stream');

foreach ($data as $row) {
// Assumes that $row will be an array.
// Manipulate the data in $row if necessary.
fputcsv($fp, $row);
}

?

So far, it has worked pretty well and is much faster than any other
way I have found to output the CSV data by iterating through the
arrays manually.

Andrew

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



Re: [PHP] Array to csv or excel in php

2010-04-19 Thread Peter Lind
On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis
 vlachakis.mano...@gmail.com wrote:
 hallo there everyone..
 i got an array from my database
 Help with Code 
 Tagshttp://www.daniweb.com/forums/misc-explaincode.html?TB_iframe=trueheight=400width=680
 *PHP Syntax* (Toggle Plain 
 Texthttp://www.daniweb.com/forums/post1194347.html#
 )


   1. $save=split([|;],$listOfItems);


 and what i want i s after making some changes to the attributes on the array
 above to export them on an csv or excel format
 but directly as a message to the browser ..
 i dont want it to be saved on the server ...
 what i cant understand from the examples i found on the net ..
 is how to handle the files and which are created cause
 i just have the array in a php file nothing more...


 another thing i have in mind is to export from the ldap server the files
 directly but seems to me as the wrong way to do it

 thanks


 Often when outputting csv, I usually do something like this:

 ?php

 $fp = fopen('php://output', 'w') or die('Could not open stream');

 foreach ($data as $row) {
    // Assumes that $row will be an array.
    // Manipulate the data in $row if necessary.
    fputcsv($fp, $row);
 }

 ?

An interesting idea. I'd do:

echo implode(',', $row);

regards
Peter

-- 
hype
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
Flickr: http://www.flickr.com/photos/fake51
BeWelcome: Fake51
Couchsurfing: Fake51
/hype

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



Re: [PHP] Array to csv or excel in php

2010-04-19 Thread Andrew Ballard
On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote:
 On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis
   1. $save=split([|;],$listOfItems);

 and what i want i s after making some changes to the attributes on the array
 above to export them on an csv or excel format
 but directly as a message to the browser ..
 i dont want it to be saved on the server ...

 Often when outputting csv, I usually do something like this:

 ?php

 $fp = fopen('php://output', 'w') or die('Could not open stream');

 foreach ($data as $row) {
    // Assumes that $row will be an array.
    // Manipulate the data in $row if necessary.
    fputcsv($fp, $row);
 }

 ?

 An interesting idea. I'd do:

 echo implode(',', $row);


If it's very simple data that works, but it doesn't allow for the
optional enclosure characters that fputcsv() uses in cases where a
data element includes the column and/or row delimiter characters. I
had originally written something using an array_map callback that did
the optional enclosures as needed and then used echo implode() as you
suggest, but found the solution I posted was shorter and faster. YMMV

Andrew

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



Re: [PHP] Array to csv or excel in php

2010-04-19 Thread Peter Lind
On 19 April 2010 17:40, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote:
 On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis
   1. $save=split([|;],$listOfItems);

 and what i want i s after making some changes to the attributes on the 
 array
 above to export them on an csv or excel format
 but directly as a message to the browser ..
 i dont want it to be saved on the server ...

 Often when outputting csv, I usually do something like this:

 ?php

 $fp = fopen('php://output', 'w') or die('Could not open stream');

 foreach ($data as $row) {
    // Assumes that $row will be an array.
    // Manipulate the data in $row if necessary.
    fputcsv($fp, $row);
 }

 ?

 An interesting idea. I'd do:

 echo implode(',', $row);


 If it's very simple data that works, but it doesn't allow for the
 optional enclosure characters that fputcsv() uses in cases where a
 data element includes the column and/or row delimiter characters. I
 had originally written something using an array_map callback that did
 the optional enclosures as needed and then used echo implode() as you
 suggest, but found the solution I posted was shorter and faster. YMMV

 Andrew


Yeah, was considering that point as well. I'd use the echo if the
array values are getting modified anyway. Otherwise your solution is
probably simpler.

Regards
Peter

-- 
hype
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
Flickr: http://www.flickr.com/photos/fake51
BeWelcome: Fake51
Couchsurfing: Fake51
/hype

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



Re: [PHP] Array to csv or excel in php

2010-04-19 Thread Ken Guest
For non-simple data I have been using PEAR's File_CSV package. It's
proven itself very useful in
regards to not having to determine in my own code whether something
needs to be quoted etc etc - especially if the output CSV needs to be
wholly RFC 4180 compliant.

The documentation of it is rather minimal - at the moment you are
dependant on the test/example files and the API docs but grokking how
to use it is rather easy.


k.

On Mon, Apr 19, 2010 at 4:40 PM, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote:
 On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote:
 On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis
   1. $save=split([|;],$listOfItems);

 and what i want i s after making some changes to the attributes on the 
 array
 above to export them on an csv or excel format
 but directly as a message to the browser ..
 i dont want it to be saved on the server ...

 Often when outputting csv, I usually do something like this:

 ?php

 $fp = fopen('php://output', 'w') or die('Could not open stream');

 foreach ($data as $row) {
    // Assumes that $row will be an array.
    // Manipulate the data in $row if necessary.
    fputcsv($fp, $row);
 }

 ?

 An interesting idea. I'd do:

 echo implode(',', $row);


 If it's very simple data that works, but it doesn't allow for the
 optional enclosure characters that fputcsv() uses in cases where a
 data element includes the column and/or row delimiter characters. I
 had originally written something using an array_map callback that did
 the optional enclosures as needed and then used echo implode() as you
 suggest, but found the solution I posted was shorter and faster. YMMV

 Andrew

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





-- 
http://blogs.linux.ie/kenguest/

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



RE: [PHP] Array to csv or excel in php

2010-04-19 Thread Jay Blanchard
[snip] to export them on an csv or excel format[/snip]

Stupid browser tricks

http://www.evolt.org/node/26896


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



Re: [PHP] Array differences

2010-04-14 Thread Ashley Sheridan
On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:

 I have the following scenario:
 
  
 
  $array1 = array(12, 34, 56, 78, 90);
 
  $array2 = array(12, 23, 56, 78, 89);
 
  
 
  $result = array_diff($array1, $array2);
 
  
 
  print_r($result);
 
  
 
 
 
 This returns:
 
  
 
  Array
 
  (
 
  [1] = 34
 
  [4] = 90
 
  )
 
  
 
 
 
 However what I really want is a two-way comparison.  I want elements that
 don't exist in either to be returned:
 
  
 
 34 and 90 because they don't exist in $array2, AND 23 and 89 because they
 don't exist in $array1.  So, is that a two step process of first doing an
 array_diff($array1, $array2) then reverse it by doing array_diff($array2,
 $array1) and merge/unique the results?  Any caveats with that?
 
  
 
  $array1 = array(12, 34, 56, 78, 90);
 
  $array2 = array(12, 23, 56, 78, 89);
 
  
 
  $diff1 = array_diff($array1, $array2);
 
  $diff2 = array_diff($array2, $array1);
 
  
 
  $result = array_unique(array_merge($diff1, $diff2));
 
  
 
  print_r($result);
 
  
 
 
 
 -- A
 


I don't see any problems with doing it that way. This will only work as
you intended if both arrays have the same number of elements I believe,
otherwise you might end up with a situation where your final array has
duplicates of the same number:

$array1 = $array(1, 2, 3, 4, 5, 6);
$array2 = $aray(1, 3, 2, 5);

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




Re: [PHP] Array differences

2010-04-14 Thread Nathan Rixham
Ashley Sheridan wrote:
 On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:

 However what I really want is a two-way comparison.  I want elements that
 don't exist in either to be returned:

 
 
 I don't see any problems with doing it that way. 

By some freak chance I made an array diff class about 2 weeks ago which
covers what you need. attached :)

usage:

$diff = new ArrayDiff( $old , $new );
$diff-l; // deleted items
$diff-r; // inserted items
$diff-u; // unchanged items

The script is optimised for huge arrays, thus it's slower for small
arrays than the usual array_diff but with large arrays it's quicker.

Regards

Nathan

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

Re: [PHP] Array differences

2010-04-14 Thread Rene Veerman
On Wed, Apr 14, 2010 at 12:03 PM, Nathan Rixham nrix...@gmail.com wrote:
 Ashley Sheridan wrote:
 On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:

 However what I really want is a two-way comparison.  I want elements that
 don't exist in either to be returned:



 I don't see any problems with doing it that way.

 By some freak chance I made an array diff class about 2 weeks ago which
 covers what you need. attached :)

 usage:

 $diff = new ArrayDiff( $old , $new );
 $diff-l; // deleted items
 $diff-r; // inserted items
 $diff-u; // unchanged items

 The script is optimised for huge arrays, thus it's slower for small
 arrays than the usual array_diff but with large arrays it's quicker.

 Regards

 Nathan


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


nice one :) i'll put it in a work-preperation folder for
htmlMicroscope then, one of these days :)

-- 
-
Greetings from Rene7705,

I have made some free open source webcomponents designed
and written by me available through:
http://code.google.com/u/rene7705/ , or
http://mediabeez.ws (latest dev versions, currently offline)

Personal info about me is available through http://www.facebook.com/rene7705
-

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



Re: [PHP] Array differences

2010-04-14 Thread Ashley M. Kirchner

On 4/14/2010 2:39 AM, Ashley Sheridan wrote:

On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:

  $array1 = array(12, 34, 56, 78, 90);
  $array2 = array(12, 23, 56, 78, 89);

  $diff1 = array_diff($array1, $array2);
  $diff2 = array_diff($array2, $array1);

  $result = array_unique(array_merge($diff1, $diff2));

  print_r($result);
 


I don't see any problems with doing it that way. This will only work 
as you intended if both arrays have the same number of elements I 
believe, otherwise you might end up with a situation where your final 
array has duplicates of the same number:


$array1 = $array(1, 2, 3, 4, 5, 6);
$array2 = $aray(1, 3, 2, 5);


Wouldn't array_unique() take care of that though?  Your example 
above returns 4 and 6, which would be correct.


A

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



Re: [PHP] Array differences

2010-04-14 Thread Ryan Sun
Maybe this one works?
array_diff(array_unique($array1 + $array2), array_intersect($array1, $array2))

On Wed, Apr 14, 2010 at 4:39 AM, Ashley Sheridan
a...@ashleysheridan.co.uk wrote:
 On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:

 I have the following scenario:



      $array1 = array(12, 34, 56, 78, 90);

      $array2 = array(12, 23, 56, 78, 89);



      $result = array_diff($array1, $array2);



      print_r($result);





 This returns:



      Array

      (

          [1] = 34

          [4] = 90

      )





 However what I really want is a two-way comparison.  I want elements that
 don't exist in either to be returned:



 34 and 90 because they don't exist in $array2, AND 23 and 89 because they
 don't exist in $array1.  So, is that a two step process of first doing an
 array_diff($array1, $array2) then reverse it by doing array_diff($array2,
 $array1) and merge/unique the results?  Any caveats with that?



      $array1 = array(12, 34, 56, 78, 90);

      $array2 = array(12, 23, 56, 78, 89);



      $diff1 = array_diff($array1, $array2);

      $diff2 = array_diff($array2, $array1);



      $result = array_unique(array_merge($diff1, $diff2));



      print_r($result);





 -- A



 I don't see any problems with doing it that way. This will only work as
 you intended if both arrays have the same number of elements I believe,
 otherwise you might end up with a situation where your final array has
 duplicates of the same number:

 $array1 = $array(1, 2, 3, 4, 5, 6);
 $array2 = $aray(1, 3, 2, 5);

 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] Array differences

2010-04-14 Thread Ashley M. Kirchner
No because that only does a one-way comparison.  It only tells me what's
missing from $array2.  I need it from both arrays.  That's why I'm comparing
1 versus 2, then 2 versus 1, and then doing a merge/unique on the result.

$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(1, 3, 2, 8, 9);
$result = array_diff(array_unique($array1 + $array2),
array_intersect($array1, $array2));

= (4, 5, 6)


Versus:

$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(1, 3, 2, 8, 9);
$diff1  = array_diff($array1, $array2);
$diff2  = array_diff($array2, $array1);
$result = array_unique(array_merge($diff1, $diff2));

= (4, 5, 6, 8, 9)

This second $result is what I want.  So far I haven't noticed any problems
doing it this way ... yet.  I'm sure someone will tell me otherwise.

Ash

 -Original Message-
 From: Ryan Sun [mailto:ryansu...@gmail.com]
 Sent: Wednesday, April 14, 2010 8:45 AM
 To: a...@ashleysheridan.co.uk
 Cc: Ashley M. Kirchner; php-general@lists.php.net
 Subject: Re: [PHP] Array differences
 
 Maybe this one works?
 array_diff(array_unique($array1 + $array2), array_intersect($array1,
 $array2))
 
 On Wed, Apr 14, 2010 at 4:39 AM, Ashley Sheridan
 a...@ashleysheridan.co.uk wrote:
  On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote:
 
  I have the following scenario:
 
 
 
       $array1 = array(12, 34, 56, 78, 90);
 
       $array2 = array(12, 23, 56, 78, 89);
 
 
 
       $result = array_diff($array1, $array2);
 
 
 
       print_r($result);
 
 
 
 
 
  This returns:
 
 
 
       Array
 
       (
 
           [1] = 34
 
           [4] = 90
 
       )
 
 
 
 
 
  However what I really want is a two-way comparison.  I want elements
 that
  don't exist in either to be returned:
 
 
 
  34 and 90 because they don't exist in $array2, AND 23 and 89 because
 they
  don't exist in $array1.  So, is that a two step process of first
 doing an
  array_diff($array1, $array2) then reverse it by doing
 array_diff($array2,
  $array1) and merge/unique the results?  Any caveats with that?
 
 
 
       $array1 = array(12, 34, 56, 78, 90);
 
       $array2 = array(12, 23, 56, 78, 89);
 
 
 
       $diff1 = array_diff($array1, $array2);
 
       $diff2 = array_diff($array2, $array1);
 
 
 
       $result = array_unique(array_merge($diff1, $diff2));
 
 
 
       print_r($result);
 
 
 
 
 
  -- A
 
 
 
  I don't see any problems with doing it that way. This will only work
 as
  you intended if both arrays have the same number of elements I
 believe,
  otherwise you might end up with a situation where your final array
 has
  duplicates of the same number:
 
  $array1 = $array(1, 2, 3, 4, 5, 6);
  $array2 = $aray(1, 3, 2, 5);
 
  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] Array differences

2010-04-14 Thread lala

Ashley M. Kirchner wrote:


$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(1, 3, 2, 8, 9);
$diff1  = array_diff($array1, $array2);
$diff2  = array_diff($array2, $array1);
$result = array_unique(array_merge($diff1, $diff2));

= (4, 5, 6, 8, 9)


Hi Ash,

Isn't the array_unique() unnecessary?

Mike

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



RE: [PHP] Array differences

2010-04-14 Thread Ashley M. Kirchner
 -Original Message-
 From: lala [mailto:l...@mail.theorb.net]
 Sent: Wednesday, April 14, 2010 10:15 AM
 To: Ashley M. Kirchner
 Cc: php-general@lists.php.net
 Subject: Re: [PHP] Array differences
 
 Ashley M. Kirchner wrote:
 
  $array1 = array(1, 2, 3, 4, 5, 6);
  $array2 = array(1, 3, 2, 8, 9);
  $diff1  = array_diff($array1, $array2);
  $diff2  = array_diff($array2, $array1);
  $result = array_unique(array_merge($diff1, $diff2));
 
  = (4, 5, 6, 8, 9)
 
 Hi Ash,
 
 Isn't the array_unique() unnecessary?
 
 Mike


Thinking about it, it should be unnecessary, but at the same time I want to 
absolutely sure that I get unique values out of the two diffs.

Ash


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



[PHP] Array differences

2010-04-13 Thread Ashley M. Kirchner
I have the following scenario:

 

 $array1 = array(12, 34, 56, 78, 90);

 $array2 = array(12, 23, 56, 78, 89);

 

 $result = array_diff($array1, $array2);

 

 print_r($result);

 

 

This returns:

 

 Array

 (

 [1] = 34

 [4] = 90

 )

 

 

However what I really want is a two-way comparison.  I want elements that
don't exist in either to be returned:

 

34 and 90 because they don't exist in $array2, AND 23 and 89 because they
don't exist in $array1.  So, is that a two step process of first doing an
array_diff($array1, $array2) then reverse it by doing array_diff($array2,
$array1) and merge/unique the results?  Any caveats with that?

 

 $array1 = array(12, 34, 56, 78, 90);

 $array2 = array(12, 23, 56, 78, 89);

 

 $diff1 = array_diff($array1, $array2);

 $diff2 = array_diff($array2, $array1);

 

 $result = array_unique(array_merge($diff1, $diff2));

 

 print_r($result);

 

 

-- A



Re: [PHP] Array differences

2010-04-13 Thread Rene Veerman
On Wed, Apr 14, 2010 at 7:01 AM, Ashley M. Kirchner ash...@pcraft.com wrote:
 I have the following scenario:



     $array1 = array(12, 34, 56, 78, 90);

     $array2 = array(12, 23, 56, 78, 89);



     $result = array_diff($array1, $array2);



     print_r($result);





 This returns:



     Array

     (

         [1] = 34

         [4] = 90

     )





 However what I really want is a two-way comparison.  I want elements that
 don't exist in either to be returned:



 34 and 90 because they don't exist in $array2, AND 23 and 89 because they
 don't exist in $array1.  So, is that a two step process of first doing an
 array_diff($array1, $array2) then reverse it by doing array_diff($array2,
 $array1) and merge/unique the results?  Any caveats with that?



     $array1 = array(12, 34, 56, 78, 90);

     $array2 = array(12, 23, 56, 78, 89);



     $diff1 = array_diff($array1, $array2);

     $diff2 = array_diff($array2, $array1);



     $result = array_unique(array_merge($diff1, $diff2));



     print_r($result);





 -- A



ok, adding this to the todo-list for htmlMicroscope... ETA on delivery
of 1.3.0-final: about 2 to 3 months i'm afraid.
Gotta get a new laundromat for my home too and stuff like that :)

-- 
-
Greetings from Rene7705,

I have made some free open source webcomponents designed
and written by me available through:
http://code.google.com/u/rene7705/ , or
http://mediabeez.ws (latest dev versions, currently offline)

Personal info about me is available through http://www.facebook.com/rene7705
-

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



[PHP] array or list of objects of different types

2010-04-02 Thread Php Developer
Hi all,

I want to be able to have an array of elements of different types. As an 
example: the first element is a boolean, the second is an integer, and the 
thirs is a string.

In php there is no typing, i'm just wondering if there is a way to have that, 
it would be a lot better than having an array of strings and have to convert 
each element.

Thank you



  __
The new Internet Explorer® 8 - Faster, safer, easier.  Optimized for Yahoo!  
Get it Now for Free! at http://downloads.yahoo.com/ca/internetexplorer/

RE: [PHP] Array Search Problem

2010-03-11 Thread Alice Wei

Hi, 

  At the time when I am writing this, looks like I already got the functions I 
needed. It turned out that I had to use some array_combine, sorting the items 
by keys instead of values as well as using array_keys to get the values I 
needed. 

Thanks for pointing me towards the right direction. 

Alice


 From: rene7...@gmail.com
 Date: Thu, 11 Mar 2010 07:12:15 +0100
 Subject: Re: [PHP] Array Search Problem
 To: aj...@alumni.iu.edu
 CC: php-general@lists.php.net
 
 (almost) all the tricks are in the comments of the help page for a
 function, on php.net
 
 but all functions accept only a given (and usually documented) set of
 parameter(type)s, so you'll probably have to prepare the var, or even
 call the function in a loop, outputting to yet another descriptively
 named array that'll be used as wanted list later in the code.
 
 On Wed, Mar 10, 2010 at 6:57 PM, Alice Wei aj...@alumni.iu.edu wrote:
 
  did you read the help for those functions on php.net?
 
  Yes, I found a recursive way to find out the index like I wanted, by
  doing something like
 
  $from = explode(-, $from);
  $state_colors= explode(-, $state_colors);
  $change = explode(-,$change);
 
  $count = count($new_array);
  $i=0;
  foreach ($new_array as $key = $value){
   echo $i .   . $key .  is  . $value .  miles awaybr /;
   $i++;
  }
 
  You can see it is not very elegant, and plus, I created the $new_array so I
  could do the ordering according to the values of the change array. I can
  tell that since this is not a single array, which is probably why
  array_search does not work.
  Since I don't need the value of my new_array here, I am still finding
  out how to strip off the values here without having to flatten my array.
  Is what I am trying to do here possible? Or, is there a trick in
  array_search that I could use to find the index without having to strip off
  anything?
 
  Thanks for your help.
 
  Alice
 
 
  On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote:
  
   Hi,
  
I have the code as shown in the following that I am trying to create
   the image of based on the file loaded into the file and additional edits.
   The problem here appears to be that no matter what value I have in the
   $distance_to_destination variable, it does not affect any changes on the
   map. What I am trying to do here is to create a map based on the 
   pre-passed
   through colors of individual states from another program, but I have to
   match up the colors based on the values of the correct states.
  
I figured that I may have problems with
  
  $key= array_search($location2,$from); //Find out the position of the
   index in the array
  
  $colors_style = ;fill: . $state_colors[$key];  //Use the index from
   array_search to apply to the color index
  
   Obviously, it is not applying the colors to the states that I would like
   other than doing it one by one as the order of what is in the $from
   variable. Could someone please give me some hints on how I could do the
   array_search here based on the value of the values in the
   $distance_to_distance and apply the color to the states?
  
   ?php
  
   header(Content-type: image/svg+xml); //Outputting an SVG
  
   $from = $_GET['from'];
   $state_colors= $_GET['state_colors'];
   $distance_to_destination= $_GET['distance_to_destination'];
  
   $from = explode(-, $from);
   $state_colors= explode(-, $state_colors);
   $change = explode(-,$change);
  
   #Load the Map
   $ourFileName= USA_Counties_with_FIPS_and_names.svg;
   $fh = fopen($ourFileName, r) or die(Can't open file);
   $contents = fread($fh,filesize($ourFileName));
   $lines2= file($ourFileName);
  
   foreach ($lines2 as $line_num = $line2) {
  
   $style_line_num = $line_num+3;
   $line2 = trim($line2);
  
if(preg_match(/^style/,$line2)) {
  
 $rest = substr($line2,0,-1);
  
 for ($j=$line_num;$j=$style_line_num;$j++){
   if(preg_match(/inkscape:label/,$lines2[$j])) {
  $location = explode(=,$lines2[$j]);
  $location2 = substr($location[1],1,-6);
  
  if(in_array($location2, $from)) {
  
   $key= array_search($location2,$from); //Find out the
   position of the index in the array
   $colors_style = ;fill: . $state_colors[$key];  //Use the
   index from array_search to apply to the color index
   $rest2 = substr($line2,0,-1). $colors_style . \;
   echo $rest2 . \n;
  }
  else echo $line2 . \n;
  
   } //end preg_match inkscape
   } //end for loop
 }  //If preg_match style
  
   else echo $line2 . \n; //else if preg_match style
} //end for each
  
   fclose($fh);
   ?
  
   Thanks for your help.
  
   Alice
  
   _
   Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
   http://clk.atdmt.com/GBL/go/201469226/direct/01

[PHP] Array Search Problem

2010-03-10 Thread Alice Wei

Hi, 

  I have the code as shown in the following that I am trying to create the 
image of based on the file loaded into the file and additional edits. The 
problem here appears to be that no matter what value I have in the 
$distance_to_destination variable, it does not affect any changes on the map. 
What I am trying to do here is to create a map based on the pre-passed through 
colors of individual states from another program, but I have to match up the 
colors based on the values of the correct states. 

  I figured that I may have problems with 

$key= array_search($location2,$from); //Find out the position of the index 
in the array

$colors_style = ;fill: . $state_colors[$key];  //Use the index from 
array_search to apply to the color index

Obviously, it is not applying the colors to the states that I would like other 
than doing it one by one as the order of what is in the $from variable. Could 
someone please give me some hints on how I could do the array_search here based 
on the value of the values in the $distance_to_distance and apply the color 
to the states?

?php

header(Content-type: image/svg+xml); //Outputting an SVG

$from = $_GET['from'];
$state_colors= $_GET['state_colors'];
$distance_to_destination= $_GET['distance_to_destination'];

$from = explode(-, $from);
$state_colors= explode(-, $state_colors);
$change = explode(-,$change);

#Load the Map
$ourFileName= USA_Counties_with_FIPS_and_names.svg;
$fh = fopen($ourFileName, r) or die(Can't open file);
$contents = fread($fh,filesize($ourFileName));
$lines2= file($ourFileName);

foreach ($lines2 as $line_num = $line2) {

$style_line_num = $line_num+3;
$line2 = trim($line2);

  if(preg_match(/^style/,$line2)) {

   $rest = substr($line2,0,-1); 

   for ($j=$line_num;$j=$style_line_num;$j++){
 if(preg_match(/inkscape:label/,$lines2[$j])) { 
$location = explode(=,$lines2[$j]);
$location2 = substr($location[1],1,-6); 
  
if(in_array($location2, $from)) {
  
 $key= array_search($location2,$from); //Find out the position of 
the index in the array
 $colors_style = ;fill: . $state_colors[$key];  //Use the index 
from array_search to apply to the color index
 $rest2 = substr($line2,0,-1). $colors_style . \;   
 echo $rest2 . \n;
}
else echo $line2 . \n;

 } //end preg_match inkscape   
 } //end for loop
   }  //If preg_match style

 else echo $line2 . \n; //else if preg_match style
 } //end for each   

fclose($fh);
?

Thanks for your help.

Alice
  
_
Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
http://clk.atdmt.com/GBL/go/201469226/direct/01/

[PHP] Array Search Not Working?

2010-03-10 Thread Alice Wei

Hi,

  I have two arrays here that I have combined into a new array, as shown here:

$from = explode(-, $from);
$change = explode(-,$change);
$new_array = array_combine($from,$change);

I then tried reading it from a file and do string matches, trying to find out 
the key using the array_search of the individual array elements. I seem to 
have no such luck, even when I copied one of the elements after I do a 
print_r($new_array); 

Here is the code,

foreach ($lines2 as $line_num = $line2) { 
$style_line_num = $line_num+3;

  if(preg_match(/^style/,$line2)) {
   
if(preg_match(/inkscape:label/,$lines2[$style_line_num])) {  
$location = explode(=,$lines2[$style_line_num]);
$location2 = substr($patient_location[1],1,-6);  
 
 if(in_array($location2, $from)) {  
 $key= array_search($location2,$new_array); //Find out the position 
of the index in the array
 echo Key  . $key . br;  //This only gives me a blank space 
after the word Key
 
} 

 } //end preg_match inkscape   
   }  //If preg_match style

I looked at the example from 
http://php.net/manual/en/function.array-search.php, and looks like what I am 
trying to do here is possible, and yet, why am I not getting a proper key 
return?

Thanks for your help.

Alice
  
_
Hotmail: Powerful Free email with security by Microsoft.
http://clk.atdmt.com/GBL/go/201469230/direct/01/

Re: [PHP] Array Search Problem

2010-03-10 Thread Rene Veerman
did you read the help for those functions on php.net?

On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote:

 Hi,

  I have the code as shown in the following that I am trying to create the 
 image of based on the file loaded into the file and additional edits. The 
 problem here appears to be that no matter what value I have in the 
 $distance_to_destination variable, it does not affect any changes on the map. 
 What I am trying to do here is to create a map based on the pre-passed 
 through colors of individual states from another program, but I have to match 
 up the colors based on the values of the correct states.

  I figured that I may have problems with

    $key= array_search($location2,$from); //Find out the position of the index 
 in the array

    $colors_style = ;fill: . $state_colors[$key];  //Use the index from 
 array_search to apply to the color index

 Obviously, it is not applying the colors to the states that I would like 
 other than doing it one by one as the order of what is in the $from variable. 
 Could someone please give me some hints on how I could do the array_search 
 here based on the value of the values in the $distance_to_distance and 
 apply the color to the states?

 ?php

 header(Content-type: image/svg+xml); //Outputting an SVG

 $from = $_GET['from'];
 $state_colors= $_GET['state_colors'];
 $distance_to_destination= $_GET['distance_to_destination'];

 $from = explode(-, $from);
 $state_colors= explode(-, $state_colors);
 $change = explode(-,$change);

 #Load the Map
 $ourFileName= USA_Counties_with_FIPS_and_names.svg;
 $fh = fopen($ourFileName, r) or die(Can't open file);
 $contents = fread($fh,filesize($ourFileName));
 $lines2= file($ourFileName);

 foreach ($lines2 as $line_num = $line2) {

 $style_line_num = $line_num+3;
 $line2 = trim($line2);

      if(preg_match(/^style/,$line2)) {

       $rest = substr($line2,0,-1);

       for ($j=$line_num;$j=$style_line_num;$j++){
         if(preg_match(/inkscape:label/,$lines2[$j])) {
            $location = explode(=,$lines2[$j]);
            $location2 = substr($location[1],1,-6);

            if(in_array($location2, $from)) {

             $key= array_search($location2,$from); //Find out the position of 
 the index in the array
             $colors_style = ;fill: . $state_colors[$key];  //Use the index 
 from array_search to apply to the color index
             $rest2 = substr($line2,0,-1). $colors_style . \;
             echo $rest2 . \n;
            }
            else echo $line2 . \n;

         } //end preg_match inkscape
     } //end for loop
   }  //If preg_match style

     else echo $line2 . \n; //else if preg_match style
  } //end for each

 fclose($fh);
 ?

 Thanks for your help.

 Alice

 _
 Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
 http://clk.atdmt.com/GBL/go/201469226/direct/01/

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



RE: [PHP] Array Search Problem

2010-03-10 Thread Alice Wei

 
 did you read the help for those functions on php.net?

Yes, I found a recursive way to find out the index like I wanted, by doing 
something like 

$from = explode(-, $from);
$state_colors= explode(-, $state_colors);
$change = explode(-,$change);

$count = count($new_array);
$i=0;
foreach ($new_array as $key = $value){
 echo $i .   . $key .  is  . $value .  miles awaybr /;
 $i++;
}

You can see it is not very elegant, and plus, I created the $new_array so I 
could do the ordering according to the values of the change array. I can tell 
that since this is not a single array, which is probably why array_search does 
not work. 
Since I don't need the value of my new_array here, I am still finding out 
how to strip off the values here without having to flatten my array. Is what 
I am trying to do here possible? Or, is there a trick in array_search that I 
could use to find the index without having to strip off anything?

Thanks for your help.

Alice

 
 On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote:
 
  Hi,
 
   I have the code as shown in the following that I am trying to create the 
  image of based on the file loaded into the file and additional edits. The 
  problem here appears to be that no matter what value I have in the 
  $distance_to_destination variable, it does not affect any changes on the 
  map. What I am trying to do here is to create a map based on the pre-passed 
  through colors of individual states from another program, but I have to 
  match up the colors based on the values of the correct states.
 
   I figured that I may have problems with
 
 $key= array_search($location2,$from); //Find out the position of the 
  index in the array
 
 $colors_style = ;fill: . $state_colors[$key];  //Use the index from 
  array_search to apply to the color index
 
  Obviously, it is not applying the colors to the states that I would like 
  other than doing it one by one as the order of what is in the $from 
  variable. Could someone please give me some hints on how I could do the 
  array_search here based on the value of the values in the 
  $distance_to_distance and apply the color to the states?
 
  ?php
 
  header(Content-type: image/svg+xml); //Outputting an SVG
 
  $from = $_GET['from'];
  $state_colors= $_GET['state_colors'];
  $distance_to_destination= $_GET['distance_to_destination'];
 
  $from = explode(-, $from);
  $state_colors= explode(-, $state_colors);
  $change = explode(-,$change);
 
  #Load the Map
  $ourFileName= USA_Counties_with_FIPS_and_names.svg;
  $fh = fopen($ourFileName, r) or die(Can't open file);
  $contents = fread($fh,filesize($ourFileName));
  $lines2= file($ourFileName);
 
  foreach ($lines2 as $line_num = $line2) {
 
  $style_line_num = $line_num+3;
  $line2 = trim($line2);
 
   if(preg_match(/^style/,$line2)) {
 
$rest = substr($line2,0,-1);
 
for ($j=$line_num;$j=$style_line_num;$j++){
  if(preg_match(/inkscape:label/,$lines2[$j])) {
 $location = explode(=,$lines2[$j]);
 $location2 = substr($location[1],1,-6);
 
 if(in_array($location2, $from)) {
 
  $key= array_search($location2,$from); //Find out the position 
  of the index in the array
  $colors_style = ;fill: . $state_colors[$key];  //Use the 
  index from array_search to apply to the color index
  $rest2 = substr($line2,0,-1). $colors_style . \;
  echo $rest2 . \n;
 }
 else echo $line2 . \n;
 
  } //end preg_match inkscape
  } //end for loop
}  //If preg_match style
 
  else echo $line2 . \n; //else if preg_match style
   } //end for each
 
  fclose($fh);
  ?
 
  Thanks for your help.
 
  Alice
 
  _
  Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
  http://clk.atdmt.com/GBL/go/201469226/direct/01/
  
_
Hotmail: Powerful Free email with security by Microsoft.
http://clk.atdmt.com/GBL/go/201469230/direct/01/

Re: [PHP] Array Search Problem

2010-03-10 Thread Rene Veerman
(almost) all the tricks are in the comments of the help page for a
function, on php.net

but all functions accept only a given (and usually documented) set of
parameter(type)s, so you'll probably have to prepare the var, or even
call the function in a loop, outputting to yet another descriptively
named array that'll be used as wanted list later in the code.

On Wed, Mar 10, 2010 at 6:57 PM, Alice Wei aj...@alumni.iu.edu wrote:

 did you read the help for those functions on php.net?

 Yes, I found a recursive way to find out the index like I wanted, by
 doing something like

 $from = explode(-, $from);
 $state_colors= explode(-, $state_colors);
 $change = explode(-,$change);

 $count = count($new_array);
 $i=0;
 foreach ($new_array as $key = $value){
  echo $i .   . $key .  is  . $value .  miles awaybr /;
  $i++;
 }

 You can see it is not very elegant, and plus, I created the $new_array so I
 could do the ordering according to the values of the change array. I can
 tell that since this is not a single array, which is probably why
 array_search does not work.
 Since I don't need the value of my new_array here, I am still finding
 out how to strip off the values here without having to flatten my array.
 Is what I am trying to do here possible? Or, is there a trick in
 array_search that I could use to find the index without having to strip off
 anything?

 Thanks for your help.

 Alice


 On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote:
 
  Hi,
 
   I have the code as shown in the following that I am trying to create
  the image of based on the file loaded into the file and additional edits.
  The problem here appears to be that no matter what value I have in the
  $distance_to_destination variable, it does not affect any changes on the
  map. What I am trying to do here is to create a map based on the pre-passed
  through colors of individual states from another program, but I have to
  match up the colors based on the values of the correct states.
 
   I figured that I may have problems with
 
     $key= array_search($location2,$from); //Find out the position of the
  index in the array
 
     $colors_style = ;fill: . $state_colors[$key];  //Use the index from
  array_search to apply to the color index
 
  Obviously, it is not applying the colors to the states that I would like
  other than doing it one by one as the order of what is in the $from
  variable. Could someone please give me some hints on how I could do the
  array_search here based on the value of the values in the
  $distance_to_distance and apply the color to the states?
 
  ?php
 
  header(Content-type: image/svg+xml); //Outputting an SVG
 
  $from = $_GET['from'];
  $state_colors= $_GET['state_colors'];
  $distance_to_destination= $_GET['distance_to_destination'];
 
  $from = explode(-, $from);
  $state_colors= explode(-, $state_colors);
  $change = explode(-,$change);
 
  #Load the Map
  $ourFileName= USA_Counties_with_FIPS_and_names.svg;
  $fh = fopen($ourFileName, r) or die(Can't open file);
  $contents = fread($fh,filesize($ourFileName));
  $lines2= file($ourFileName);
 
  foreach ($lines2 as $line_num = $line2) {
 
  $style_line_num = $line_num+3;
  $line2 = trim($line2);
 
       if(preg_match(/^style/,$line2)) {
 
        $rest = substr($line2,0,-1);
 
        for ($j=$line_num;$j=$style_line_num;$j++){
          if(preg_match(/inkscape:label/,$lines2[$j])) {
             $location = explode(=,$lines2[$j]);
             $location2 = substr($location[1],1,-6);
 
             if(in_array($location2, $from)) {
 
              $key= array_search($location2,$from); //Find out the
  position of the index in the array
              $colors_style = ;fill: . $state_colors[$key];  //Use the
  index from array_search to apply to the color index
              $rest2 = substr($line2,0,-1). $colors_style . \;
              echo $rest2 . \n;
             }
             else echo $line2 . \n;
 
          } //end preg_match inkscape
      } //end for loop
    }  //If preg_match style
 
      else echo $line2 . \n; //else if preg_match style
   } //end for each
 
  fclose($fh);
  ?
 
  Thanks for your help.
 
  Alice
 
  _
  Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
  http://clk.atdmt.com/GBL/go/201469226/direct/01/

 
 Hotmail: Powerful Free email with security by Microsoft. Get it now.

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



Re: [PHP] array conversion

2010-02-20 Thread clancy_1
Or:

$a = array ('Cats', 'white', 'Dogs', 'black', 'Mice', 'grey', 'Camels', 
'brown');
$b = '';// Just in case it has some leftover 
value
$k = 2* (int) (count ($a)/2);   // ensure even no of terms
$i = 0; while ($i  $k)
{ 
$b[$a[$i++]] = $a[$i++];  // ***
}

And this works:
$i = 0; $k = array_keys($b); 
while ($i  count($b)) {echo 'h5'.$i.': '.$k[$i].' = '. 
$b[$k[$i++]].'/h5'; }

0: Cats = white
1: Dogs = black
2: Mice = grey
3: Camels = brown

( *** I have always been wary of using statements like this because I was 
unsure when the
incrementing would occur, so I tried it.)

Clancy

On Fri, 19 Feb 2010 02:26:49 -0500, simples...@gmail.com (Adam Richardson) 
wrote:

Or,

function new_arr(array $arr)
{
$count = count($arr);
if ($count % 2 != 0) throw new Exception('The new_arr() function
requires an even number of elements.');
for ($i = 0; $i  $count; $i += 2)
{
$new_arr[$arr[$i]] = $arr[$i + 1];
}
return $new_arr;
}

$test = new_arr(array('k1', 'v1', 'k2', 'v2', 'k3', 'v3'));

exit(var_dump($test));

On Fri, Feb 19, 2010 at 1:19 AM, Larry Garfield la...@garfieldtech.comwrote:

 On Thursday 18 February 2010 11:58:28 pm Paul M Foster wrote:
  On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:
   Hi guys. How to convert an array like:
  
   Array
   (
   [0] = key1
   [1] = value1
   [2] = key2
   [3] = value2
   )
  
   to
  
  
   Array
   (
   [key1] = value1
   [key2] = value2
   )
  
   Is there a built-in function to do this?
   Please Cc me. :)
   Thank you in advance.
 
  I don't believe so, but rolling your own should not be too hard:
 
  $a = array($key1, $value1, $key2, $value2);
  $b = array();
  $numitems = count($a);
 
  for ($i = 0; $i  $numitems; $i++) {
if ($i % 2 == 0) {
$saved_key = $a[$i];
}
elseif ($i % 2 == 1) {
$b[$saved_key] = $a[$i];
}
  }
 
  Code is crude and untested, but you get the idea.
 
  Paul

 This would be even shorter, I think:

 foreach ($items as $i = $value) {
  $temp[$i % 2][] = $value;
 }
 $done = array_combine($temp[0], $temp[1]);

 (Also untested, just off the cuff...)

 --Larry Garfield

 --
 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] array conversion

2010-02-19 Thread Richard Quadling
On 19 February 2010 07:26, Adam Richardson simples...@gmail.com wrote:
 Or,

 function new_arr(array $arr)
 {
    $count = count($arr);
    if ($count % 2 != 0) throw new Exception('The new_arr() function
 requires an even number of elements.');
    for ($i = 0; $i  $count; $i += 2)
    {
        $new_arr[$arr[$i]] = $arr[$i + 1];
    }
    return $new_arr;
 }

 $test = new_arr(array('k1', 'v1', 'k2', 'v2', 'k3', 'v3'));

 exit(var_dump($test));

 On Fri, Feb 19, 2010 at 1:19 AM, Larry Garfield la...@garfieldtech.comwrote:

 On Thursday 18 February 2010 11:58:28 pm Paul M Foster wrote:
  On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:
   Hi guys. How to convert an array like:
  
   Array
   (
       [0] = key1
       [1] = value1
       [2] = key2
       [3] = value2
   )
  
   to
  
  
   Array
   (
       [key1] = value1
       [key2] = value2
   )
  
   Is there a built-in function to do this?
   Please Cc me. :)
   Thank you in advance.
 
  I don't believe so, but rolling your own should not be too hard:
 
  $a = array($key1, $value1, $key2, $value2);
  $b = array();
  $numitems = count($a);
 
  for ($i = 0; $i  $numitems; $i++) {
        if ($i % 2 == 0) {
                $saved_key = $a[$i];
        }
        elseif ($i % 2 == 1) {
                $b[$saved_key] = $a[$i];
        }
  }
 
  Code is crude and untested, but you get the idea.
 
  Paul

 This would be even shorter, I think:

 foreach ($items as $i = $value) {
  $temp[$i % 2][] = $value;
 }
 $done = array_combine($temp[0], $temp[1]);

 (Also untested, just off the cuff...)

 --Larry Garfield

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




I'd say that this cat is well and truly skinned!

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




-- 
-
Richard Quadling
Standing on the shoulders of some very clever giants!
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

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



Re: [PHP] array conversion

2010-02-19 Thread tedd

At 10:48 AM + 2/19/10, Richard Quadling wrote:

On 19 February 2010 07:26, Adam Richardson simples...@gmail.com wrote:
 Or,


Code fight!!!

http://www.webbytedd.com/ccc/array/

After reviewing the entries, mine does not provide any significant 
difference. I did it as a mental exercise after looking at several 
built-in array functions (array_flip(), array_combine(), etc. ) that 
I thought might solve the problem, but didn't.


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] array conversion

2010-02-19 Thread Richard Quadling
On 19 February 2010 15:52, tedd tedd.sperl...@gmail.com wrote:
 At 10:48 AM + 2/19/10, Richard Quadling wrote:

 On 19 February 2010 07:26, Adam Richardson simples...@gmail.com wrote:
  Or,

 Code fight!!!

 http://www.webbytedd.com/ccc/array/

 After reviewing the entries, mine does not provide any significant
 difference. I did it as a mental exercise after looking at several built-in
 array functions (array_flip(), array_combine(), etc. ) that I thought might
 solve the problem, but didn't.

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


Just wanting to join in.

?php
$array = array
(
'key1',
'value1',
'key2',
'value2',
);

$result = array();
while(!is_null($result[array_shift($array)] = array_shift($array)));
array_pop($result);
print_r($result);
?

outputs ...

Array
(
[key1] = value1
[key2] = value2
)



-- 
-
Richard Quadling
Standing on the shoulders of some very clever giants!
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

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



[PHP] array conversion

2010-02-18 Thread Dasn

Hi guys. How to convert an array like:

Array
(
[0] = key1
[1] = value1
[2] = key2
[3] = value2
)

to


Array
(
[key1] = value1
[key2] = value2
)

Is there a built-in function to do this?
Please Cc me. :)
Thank you in advance.


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



Re: [PHP] array conversion

2010-02-18 Thread Paul M Foster
On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:

 Hi guys. How to convert an array like:

 Array
 (
 [0] = key1
 [1] = value1
 [2] = key2
 [3] = value2
 )

 to


 Array
 (
 [key1] = value1
 [key2] = value2
 )

 Is there a built-in function to do this?
 Please Cc me. :)
 Thank you in advance.

I don't believe so, but rolling your own should not be too hard:

$a = array($key1, $value1, $key2, $value2);
$b = array();
$numitems = count($a);

for ($i = 0; $i  $numitems; $i++) {
if ($i % 2 == 0) {
$saved_key = $a[$i];
}
elseif ($i % 2 == 1) {
$b[$saved_key] = $a[$i];
}
}

Code is crude and untested, but you get the idea.

Paul

-- 
Paul M. Foster

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



Re: [PHP] array conversion

2010-02-18 Thread Larry Garfield
On Thursday 18 February 2010 11:58:28 pm Paul M Foster wrote:
 On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:
  Hi guys. How to convert an array like:
 
  Array
  (
  [0] = key1
  [1] = value1
  [2] = key2
  [3] = value2
  )
 
  to
 
 
  Array
  (
  [key1] = value1
  [key2] = value2
  )
 
  Is there a built-in function to do this?
  Please Cc me. :)
  Thank you in advance.
 
 I don't believe so, but rolling your own should not be too hard:
 
 $a = array($key1, $value1, $key2, $value2);
 $b = array();
 $numitems = count($a);
 
 for ($i = 0; $i  $numitems; $i++) {
   if ($i % 2 == 0) {
   $saved_key = $a[$i];
   }
   elseif ($i % 2 == 1) {
   $b[$saved_key] = $a[$i];
   }
 }
 
 Code is crude and untested, but you get the idea.
 
 Paul

This would be even shorter, I think:

foreach ($items as $i = $value) {
  $temp[$i % 2][] = $value;
}
$done = array_combine($temp[0], $temp[1]);

(Also untested, just off the cuff...)

--Larry Garfield

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



Re: [PHP] array conversion

2010-02-18 Thread Adam Richardson
Or,

function new_arr(array $arr)
{
$count = count($arr);
if ($count % 2 != 0) throw new Exception('The new_arr() function
requires an even number of elements.');
for ($i = 0; $i  $count; $i += 2)
{
$new_arr[$arr[$i]] = $arr[$i + 1];
}
return $new_arr;
}

$test = new_arr(array('k1', 'v1', 'k2', 'v2', 'k3', 'v3'));

exit(var_dump($test));

On Fri, Feb 19, 2010 at 1:19 AM, Larry Garfield la...@garfieldtech.comwrote:

 On Thursday 18 February 2010 11:58:28 pm Paul M Foster wrote:
  On Fri, Feb 19, 2010 at 01:20:12PM +0800, Dasn wrote:
   Hi guys. How to convert an array like:
  
   Array
   (
   [0] = key1
   [1] = value1
   [2] = key2
   [3] = value2
   )
  
   to
  
  
   Array
   (
   [key1] = value1
   [key2] = value2
   )
  
   Is there a built-in function to do this?
   Please Cc me. :)
   Thank you in advance.
 
  I don't believe so, but rolling your own should not be too hard:
 
  $a = array($key1, $value1, $key2, $value2);
  $b = array();
  $numitems = count($a);
 
  for ($i = 0; $i  $numitems; $i++) {
if ($i % 2 == 0) {
$saved_key = $a[$i];
}
elseif ($i % 2 == 1) {
$b[$saved_key] = $a[$i];
}
  }
 
  Code is crude and untested, but you get the idea.
 
  Paul

 This would be even shorter, I think:

 foreach ($items as $i = $value) {
  $temp[$i % 2][] = $value;
 }
 $done = array_combine($temp[0], $temp[1]);

 (Also untested, just off the cuff...)

 --Larry Garfield

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




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


[PHP] Array

2009-10-24 Thread Ron Piggott
The following line gives me an error message when there aren't any
values in the array --- how do I accommodate this?

Warning: Invalid argument supplied for foreach()

foreach ($_SESSION['order'] AS $key = $value ) { 


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



Re: [PHP] Array

2009-10-24 Thread Ashley Sheridan
On Sat, 2009-10-24 at 06:57 -0400, Ron Piggott wrote:

 The following line gives me an error message when there aren't any
 values in the array --- how do I accommodate this?
 
 Warning: Invalid argument supplied for foreach()
 
 foreach ($_SESSION['order'] AS $key = $value ) { 
 
 


Do an isset() on $_SESSION['order'] first to determine if the variable
even exists, then do is_array() to determine if it's an array or not
before trying to iterate it. My guess is that $_SESSION['order'] isn't
an array all the time.

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




Re: [PHP] Array

2009-10-24 Thread Martin Scotta
On Sat, Oct 24, 2009 at 7:59 AM, Ashley Sheridan
a...@ashleysheridan.co.ukwrote:

 On Sat, 2009-10-24 at 06:57 -0400, Ron Piggott wrote:

  The following line gives me an error message when there aren't any
  values in the array --- how do I accommodate this?
 
  Warning: Invalid argument supplied for foreach()
 
  foreach ($_SESSION['order'] AS $key = $value ) {
 
 


 Do an isset() on $_SESSION['order'] first to determine if the variable
 even exists, then do is_array() to determine if it's an array or not
 before trying to iterate it. My guess is that $_SESSION['order'] isn't
 an array all the time.

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



foreach works with array and instances.
Unless the class implements Transversable, it's public properties are used
on the loop.


foreach($object as $prop = $value )
//php translates the foreach into something like this...
foreach(get_object_vars($object) as $prop = $value )

-- 
Martin Scotta


Re: [PHP] Array

2009-10-24 Thread Ron Piggott
The code I have so far for orders is below.  When a product hasn't been
added it does what I want it to --- in giving the message Your shopping
cart is empty.  When a product is added, but then the user changes
their mind I use the following lines of code to remove the selection:

UNSET($_SESSION['order'][$reference]['quantity']);
UNSET($_SESSION['order'][$reference]);

It still leaves the variable   $_SESSION['order']   as an array, even if
there are no selections in it.  The PHP command is_array is useless of
weed out when there are no products.

What I would like to have happen is if the shopping cart is empty then
the message Your shopping cart is empty be displayed 100% of the time.
How do I achieve this?  What changes to my code below need to happen?

?php
if ( isset($_SESSION['order']) ) {
#customer has begun creating order

foreach ($_SESSION['order'] AS $key = $value ) { 
echo Product:  . $key .  Quantity:  .
$_SESSION['order'][$key]['quantity'] . br\r\n;
}

} else {
#no products selected

echo ul class=\lists\\r\n;
echo liYour shopping cart is empty/li\r\n;
echo /ul\r\n;

}

-Original Message-
From: Martin Scotta martinsco...@gmail.com
To: a...@ashleysheridan.co.uk
Cc: ron.pigg...@actsministries.org, PHP General
php-general@lists.php.net
Subject: Re: [PHP] Array
Date: Sat, 24 Oct 2009 11:50:14 -0300



On Sat, Oct 24, 2009 at 7:59 AM, Ashley Sheridan
a...@ashleysheridan.co.uk wrote:
On Sat, 2009-10-24 at 06:57 -0400, Ron Piggott wrote:

 The following line gives me an error message when there aren't
any
 values in the array --- how do I accommodate this?

 Warning: Invalid argument supplied for foreach()

 foreach ($_SESSION['order'] AS $key = $value ) {






Do an isset() on $_SESSION['order'] first to determine if the
variable
even exists, then do is_array() to determine if it's an array or
not
before trying to iterate it. My guess is that $_SESSION['order']
isn't
an array all the time.



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




foreach works with array and instances. 
Unless the class implements Transversable, it's public properties are
used on the loop.


foreach($object as $prop = $value )
//php translates the foreach into something like this...
foreach(get_object_vars($object) as $prop = $value )

-- 
Martin Scotta


Re: [PHP] Array

2009-10-24 Thread Ron Piggott

AHH.  The count() command does the trick.  Ron

-Original Message-
From: Ron Piggott ron.pigg...@actsministries.org
Reply-to: ron.pigg...@actsministries.org
To: Martin Scotta martinsco...@gmail.com, phps...@gmail.com
Cc: a...@ashleysheridan.co.uk, PHP General php-general@lists.php.net
Subject: Re: [PHP] Array
Date: Sat, 24 Oct 2009 11:43:12 -0400

The code I have so far for orders is below.  When a product hasn't been
added it does what I want it to --- in giving the message Your shopping
cart is empty.  When a product is added, but then the user changes
their mind I use the following lines of code to remove the selection:

UNSET($_SESSION['order'][$reference]['quantity']);
UNSET($_SESSION['order'][$reference]);

It still leaves the variable   $_SESSION['order']   as an array, even if
there are no selections in it.  The PHP command is_array is useless of
weed out when there are no products.

What I would like to have happen is if the shopping cart is empty then
the message Your shopping cart is empty be displayed 100% of the time.
How do I achieve this?  What changes to my code below need to happen?

?php
if ( isset($_SESSION['order']) ) {
#customer has begun creating order

foreach ($_SESSION['order'] AS $key = $value ) { 
echo Product:  . $key .  Quantity:  .
$_SESSION['order'][$key]['quantity'] . br\r\n;
}

} else {
#no products selected

echo ul class=\lists\\r\n;
echo liYour shopping cart is empty/li\r\n;
echo /ul\r\n;

}

-Original Message-
From: Martin Scotta martinsco...@gmail.com
To: a...@ashleysheridan.co.uk
Cc: ron.pigg...@actsministries.org, PHP General
php-general@lists.php.net
Subject: Re: [PHP] Array
Date: Sat, 24 Oct 2009 11:50:14 -0300



On Sat, Oct 24, 2009 at 7:59 AM, Ashley Sheridan
a...@ashleysheridan.co.uk wrote: 
On Sat, 2009-10-24 at 06:57 -0400, Ron Piggott wrote:

 The following line gives me an error message when there aren't
any
 values in the array --- how do I accommodate this?

 Warning: Invalid argument supplied for foreach()

 foreach ($_SESSION['order'] AS $key = $value ) {





Do an isset() on $_SESSION['order'] first to determine if the
variable
even exists, then do is_array() to determine if it's an array or
not
before trying to iterate it. My guess is that $_SESSION['order']
isn't
an array all the time.


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




foreach works with array and instances. 
Unless the class implements Transversable, it's public properties are
used on the loop.


foreach($object as $prop = $value )
//php translates the foreach into something like this...
foreach(get_object_vars($object) as $prop = $value )

-- 
Martin Scotta


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



Re: [PHP] Array

2009-10-24 Thread Shawn McKenzie
Ron Piggott wrote:
 The code I have so far for orders is below.  When a product hasn't been
 added it does what I want it to --- in giving the message Your shopping
 cart is empty.  When a product is added, but then the user changes
 their mind I use the following lines of code to remove the selection:
 
 UNSET($_SESSION['order'][$reference]['quantity']);
 UNSET($_SESSION['order'][$reference]);
 
 It still leaves the variable   $_SESSION['order']   as an array, even if
 there are no selections in it.  The PHP command is_array is useless of
 weed out when there are no products.
 
 What I would like to have happen is if the shopping cart is empty then
 the message Your shopping cart is empty be displayed 100% of the time.
 How do I achieve this?  What changes to my code below need to happen?
 
 ?php
 if ( isset($_SESSION['order']) ) {
 #customer has begun creating order
 
 foreach ($_SESSION['order'] AS $key = $value ) { 
 echo Product:  . $key .  Quantity:  .
 $_SESSION['order'][$key]['quantity'] . br\r\n;
 }
 
 } else {
 #no products selected
 
 echo ul class=\lists\\r\n;
 echo liYour shopping cart is empty/li\r\n;
 echo /ul\r\n;
 
 }
 

Or use unset, but unset the entire order:  unset($_SESSION['order'])

-- 
Thanks!
-Shawn
http://www.spidean.com

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



Re: [PHP] Array

2009-10-24 Thread Jim Lucas

Ron Piggott wrote:

The code I have so far for orders is below.  When a product hasn't been
added it does what I want it to --- in giving the message Your shopping
cart is empty.  When a product is added, but then the user changes
their mind I use the following lines of code to remove the selection:

UNSET($_SESSION['order'][$reference]['quantity']);
UNSET($_SESSION['order'][$reference]);

It still leaves the variable   $_SESSION['order']   as an array, even if
there are no selections in it.  The PHP command is_array is useless of
weed out when there are no products.

What I would like to have happen is if the shopping cart is empty then
the message Your shopping cart is empty be displayed 100% of the time.
How do I achieve this?  What changes to my code below need to happen?

?php
if ( isset($_SESSION['order']) ) {
#customer has begun creating order

foreach ($_SESSION['order'] AS $key = $value ) { 
echo Product:  . $key .  Quantity:  .

$_SESSION['order'][$key]['quantity'] . br\r\n;
}

} else {
#no products selected

echo ul class=\lists\\r\n;
echo liYour shopping cart is empty/li\r\n;
echo /ul\r\n;

}



Try this

?php

...

if ( isset($_SESSION['order']) # Does it exist
 is_array($_SESSION['order'])  # Is it an array
 count($_SESSION['order'])  0   # Does it have at least 1 element
) {

#customer has begun creating order
foreach ($_SESSION['order'] AS $key = $value ) {
echo Product: {$key} Quantity: 
{$_SESSION['order'][$key]['quantity']}br\r\n;
}

} else {
#no products selected
echo ul class=\lists\\r\n;
echo liYour shopping cart is empty/li\r\n;
echo /ul\r\n;
}


...

?


-Original Message-
From: Martin Scotta martinsco...@gmail.com
To: a...@ashleysheridan.co.uk
Cc: ron.pigg...@actsministries.org, PHP General
php-general@lists.php.net
Subject: Re: [PHP] Array
Date: Sat, 24 Oct 2009 11:50:14 -0300



On Sat, Oct 24, 2009 at 7:59 AM, Ashley Sheridan
a...@ashleysheridan.co.uk wrote:
On Sat, 2009-10-24 at 06:57 -0400, Ron Piggott wrote:

 The following line gives me an error message when there aren't

any
 values in the array --- how do I accommodate this?

 Warning: Invalid argument supplied for foreach()

 foreach ($_SESSION['order'] AS $key = $value ) {






Do an isset() on $_SESSION['order'] first to determine if the

variable
even exists, then do is_array() to determine if it's an array or
not
before trying to iterate it. My guess is that $_SESSION['order']
isn't
an array all the time.



Thanks,

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




foreach works with array and instances. 
Unless the class implements Transversable, it's public properties are

used on the loop.


foreach($object as $prop = $value )
//php translates the foreach into something like this...
foreach(get_object_vars($object) as $prop = $value )




--
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] Array references - how to unset() ?

2009-09-03 Thread hack988 hack988
Yes,thanks and I sorry for my poor english

2009/9/3 Robert Cummings rob...@interjinn.com:
 hack988 hack988 wrote:

 Reference vars in php would not be unset if it reference by another
 var,so you must keep original var had'nt being reference.

 You can't reference a reference in PHP. If you take the reference of a
 variable that is itself a reference then you are taking a reference to the
 referenced value and not the reference variable itself. This is illustrated
 in the following example:

 ?php

 $foo = '123';
 $fee = '987';

 $blah = $foo;
 $bleh = $blah;
 $blah = $fee;

 echo 'blah: '.$blah.\n;
 echo 'bleh: '.$bleh.\n;

 ?

 What I think you meant to say, is that a value is not unset as long as it
 has at least one variable referencing it. You most certainly unset the
 reference if you apply unset to it, it is the value referenced that may
 remain.

 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



[PHP] Array references - how to unset() ?

2009-09-02 Thread Martin Zvarík

$ARR = array(
 'a' = array('b' = 'blah')
);


function set($key)
{
   global $ARR;

   foreach ($key as $i = $k) {
if ($i == 0) {
   $sourcevar = $ARR[$k];
   } else {
   $sourcevar = $sourcevar[$k];
   }
   }

// unset($sourcevar); // will cancel the reference - we want to 
unset the ['b'], but how?


$sourcevar = null; // will set it NULL, but won't unset...


foreach ($ARR ... // I could run a cleanup, that would go through all of 
the array and unset what is NULL, but I would need to use REFERENCES 
again!! array_walk_recursive() is also worthless... any ideas?



}

set( array('a', 'b') );





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



Re: [PHP] Array references - how to unset() ?

2009-09-02 Thread Robert Cummings



Martin Zvarík wrote:

$ARR = array(
  'a' = array('b' = 'blah')
);


function set($key)
{
global $ARR;

foreach ($key as $i = $k) {
 if ($i == 0) {
$sourcevar = $ARR[$k];
} else {
$sourcevar = $sourcevar[$k];
}
}

 // unset($sourcevar); // will cancel the reference - we want to 
unset the ['b'], but how?


$sourcevar = null; // will set it NULL, but won't unset...


foreach ($ARR ... // I could run a cleanup, that would go through all of 
the array and unset what is NULL, but I would need to use REFERENCES 
again!! array_walk_recursive() is also worthless... any ideas?



}

set( array('a', 'b') );


unset( $ARR[$k] )

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] Array references - how to unset() ?

2009-09-02 Thread Martin Zvarík

Robert Cummings napsal(a):



Martin Zvarík wrote:

$ARR = array(
  'a' = array('b' = 'blah')
);


function set($key)
{
global $ARR;

foreach ($key as $i = $k) {
 if ($i == 0) {
$sourcevar = $ARR[$k];
} else {
$sourcevar = $sourcevar[$k];
}
}

 // unset($sourcevar); // will cancel the reference - we want to 
unset the ['b'], but how?


$sourcevar = null; // will set it NULL, but won't unset...


foreach ($ARR ... // I could run a cleanup, that would go through all 
of the array and unset what is NULL, but I would need to use 
REFERENCES again!! array_walk_recursive() is also worthless... any 
ideas?



}

set( array('a', 'b') );


unset( $ARR[$k] )

Cheers,
Rob.

Thanks for reply, but I want to:

unset($ARR['a']['b'])

Imagine I have this:

$KEYS = array('a', 'b', 'c');

And I want to:

unset($ARR['a']['b']['c'])


It's probably impossible, unless I do something dirty like this:

list($rootA, $rootB, $rootC) = $KEYS;

if (isset($rootC)) unset($x[$rootA][$rootB][$rootC]);
elseif (isset($rootB)) unset($x[$rootA][$rootB]);
elseif (isset($rootA)) unset($x[$rootA]);






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



Re: [PHP] Array references - how to unset() ?

2009-09-02 Thread Robert Cummings

Martin Zvarík wrote:

Robert Cummings napsal(a):


Martin Zvarík wrote:

$ARR = array(
  'a' = array('b' = 'blah')
);


function set($key)
{
global $ARR;

foreach ($key as $i = $k) {
 if ($i == 0) {
$sourcevar = $ARR[$k];
} else {
$sourcevar = $sourcevar[$k];
}
}

 // unset($sourcevar); // will cancel the reference - we want to 
unset the ['b'], but how?


$sourcevar = null; // will set it NULL, but won't unset...


foreach ($ARR ... // I could run a cleanup, that would go through all 
of the array and unset what is NULL, but I would need to use 
REFERENCES again!! array_walk_recursive() is also worthless... any 
ideas?



}

set( array('a', 'b') );

unset( $ARR[$k] )

Cheers,
Rob.

Thanks for reply, but I want to:

unset($ARR['a']['b'])

Imagine I have this:

$KEYS = array('a', 'b', 'c');

And I want to:

unset($ARR['a']['b']['c'])


This is possible. You're just not giving enough consideration to your 
exit strategy :)


?php

function unset_deep( $array, $keys )
{
$final = array_pop( $keys );

foreach( $keys as $key )
{
$array = $array[$key];
}

unset( $array[$final] );
}

$value = array
(
'a' = array
(
'b' = array
(
'c' = 'C',
'd' = 'D',
'e' = 'E'
),
),
);

$keys = array('a', 'b', 'c');
unset_deep( $value, $keys );

print_r( $value );

?

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] Array references - how to unset() ?

2009-09-02 Thread Martin Zvarík

AHA !!!

OMG... how come I did not see that!?

Instead this:
$array = $array[$final];
unset($array);

This:
unset($array[$final]);


3 AM in the morning... that must be the reason! .)

Thanks.





This is possible. You're just not giving enough consideration to your 
exit strategy :)


?php

function unset_deep( $array, $keys )
{
$final = array_pop( $keys );

foreach( $keys as $key )
{
$array = $array[$key];
}

unset( $array[$final] );
}

$value = array
(
'a' = array
(
'b' = array
(
'c' = 'C',
'd' = 'D',
'e' = 'E'
),
),
);

$keys = array('a', 'b', 'c');
unset_deep( $value, $keys );

print_r( $value );

?

Cheers,
Rob.



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



[PHP] array() returns something weird

2009-08-22 Thread Szczepan Hołyszewski
Hello!

I am almost certain I am hitting some kind of bug. All of a sudden, array() 
stops returning an empty array and starts returning something weird. The weird 
thing behaves as NULL in most circumstances (e.g. gettype() says NULL), 
except:

$foo=array();  // -- weird thing returned
$foo[]=bar;

causes Fatal error: [] operator not supported for strings, which is different 
from the regular behavior of:

$foo=null;
$foo[]=bar;  // -- $foo simply becomes an array

The problem is not limited to one place in code, and indeed before the fatal 
caused by append-assignment I get several warnings like array_diff_key(): 
Argument #1 is not an array, where the offending argument receives a result of 
array().

The effect is not random, i.e. it always breaks identically when the same 
script processes the same data. However I was so far unable to create a 
minimal test case that triggers the bug. My script is rather involved, and 
here are some things it uses:

 - Exceptions
 - DOM to-fro SimpleXML
 - lots of multi-level output buffering

Disabling Zend Optimizer doesn't help. Disabling Zend Memory Manager is 
apparently impossible. Memory usage is below 10MB out of 128MB limit.

Any similar experiences? Ideas what to check for? Workarounds?

From phpinfo():

PHP Version:
5.2.9 (can't easily upgrade - shared host)

System:
FreeBSD 7.1-RELEASE-p4 FreeBSD 7.1-RELEASE-p4 #0: Wed Apr 15 15:48:43 UTC 2009  
amd64

Configure Command:
'./configure' '--enable-bcmath' '--enable-calendar' '--enable-dbase' '--enable-
exif' '--enable-fastcgi' '--enable-force-cgi-redirect' '--enable-ftp' '--
enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-
maintainer-zts' '--enable-mbstring' '--enable-pdo=shared' '--enable-safe-mode' 
'--enable-soap' '--enable-sockets' '--enable-ucd-snmp-hack' '--enable-wddx' 
'--enable-zend-multibyte' '--enable-zip' '--prefix=/usr' '--with-bz2' '--with-
curl=/opt/curlssl/' '--with-curlwrappers' '--with-freetype-dir=/usr/local' '--
with-gd' '--with-gettext' '--with-imap=/opt/php_with_imap_client/' '--with-
imap-ssl=/usr/local' '--with-jpeg-dir=/usr/local' '--with-libexpat-
dir=/usr/local' '--with-libxml-dir=/opt/xml2' '--with-libxml-dir=/opt/xml2/' 
'--with-mcrypt=/opt/libmcrypt/' '--with-mhash=/opt/mhash/' '--with-mime-magic' 
'--with-mysql=/usr/local' '--with-mysql-sock=/tmp/mysql.sock' '--with-
mysqli=/usr/local/bin/mysql_config' '--with-openssl=/usr/local' '--with-
openssl-dir=/usr/local' '--with-pdo-mysql=shared' '--with-pdo-sqlite=shared' 
'--with-pgsql=/usr/local' '--with-pic' '--with-png-dir=/usr/local' '--with-
pspell' '--with-snmp' '--with-sqlite=shared' '--with-tidy=/opt/tidy/' '--with-
ttf' '--with-xmlrpc' '--with-xpm-dir=/usr/local' '--with-xsl=/opt/xslt/' '--
with-zlib' '--with-zlib-dir=/usr'

Thanks in advance,
Szczepan Holyszewski

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



Re: [PHP] array() returns something weird

2009-08-22 Thread Lars Torben Wilson
2009/8/22 Szczepan Hołyszewski webmas...@strefarytmu.pl:
 Hello!

 I am almost certain I am hitting some kind of bug. All of a sudden, array()
 stops returning an empty array and starts returning something weird. The weird
 thing behaves as NULL in most circumstances (e.g. gettype() says NULL),
 except:

        $foo=array();      // -- weird thing returned
        $foo[]=bar;

 causes Fatal error: [] operator not supported for strings, which is 
 different
 from the regular behavior of:

Hi there,

Without seeing the actual code, it's hard to say what the problem is.
However, I'd be pretty surprised if you've actually run into a bug in
PHP--I would first suspect a bug in your code. No offense
intended--that's just how it usually plays out. :)

What it looks like to me is that something is causing $foo to be a
string before the '$foo[] = bar;' line is encountered. What do you
get if you put a gettype($foo); just before that line?

        $foo=null;
        $foo[]=bar;      // -- $foo simply becomes an array

 The problem is not limited to one place in code, and indeed before the fatal
 caused by append-assignment I get several warnings like array_diff_key():
 Argument #1 is not an array, where the offending argument receives a result 
 of
 array().

This would appear to support my suspicion, but try inserting the
gettype($foo) (or better, var_export($foo);) just before one of the
lines which triggers the error, and post the results.

Can you post the code in a .zip file or online somewhere? If not,
that's cool, but it will probably make it harder to help you track it
down if you can't.


Regards,

Torben

 The effect is not random, i.e. it always breaks identically when the same
 script processes the same data. However I was so far unable to create a
 minimal test case that triggers the bug. My script is rather involved, and
 here are some things it uses:

  - Exceptions
  - DOM to-fro SimpleXML
  - lots of multi-level output buffering

 Disabling Zend Optimizer doesn't help. Disabling Zend Memory Manager is
 apparently impossible. Memory usage is below 10MB out of 128MB limit.

 Any similar experiences? Ideas what to check for? Workarounds?

 From phpinfo():

 PHP Version:
 5.2.9 (can't easily upgrade - shared host)

 System:
 FreeBSD 7.1-RELEASE-p4 FreeBSD 7.1-RELEASE-p4 #0: Wed Apr 15 15:48:43 UTC 2009
 amd64

 Configure Command:
 './configure' '--enable-bcmath' '--enable-calendar' '--enable-dbase' 
 '--enable-
 exif' '--enable-fastcgi' '--enable-force-cgi-redirect' '--enable-ftp' '--
 enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-
 maintainer-zts' '--enable-mbstring' '--enable-pdo=shared' '--enable-safe-mode'
 '--enable-soap' '--enable-sockets' '--enable-ucd-snmp-hack' '--enable-wddx'
 '--enable-zend-multibyte' '--enable-zip' '--prefix=/usr' '--with-bz2' '--with-
 curl=/opt/curlssl/' '--with-curlwrappers' '--with-freetype-dir=/usr/local' '--
 with-gd' '--with-gettext' '--with-imap=/opt/php_with_imap_client/' '--with-
 imap-ssl=/usr/local' '--with-jpeg-dir=/usr/local' '--with-libexpat-
 dir=/usr/local' '--with-libxml-dir=/opt/xml2' '--with-libxml-dir=/opt/xml2/'
 '--with-mcrypt=/opt/libmcrypt/' '--with-mhash=/opt/mhash/' '--with-mime-magic'
 '--with-mysql=/usr/local' '--with-mysql-sock=/tmp/mysql.sock' '--with-
 mysqli=/usr/local/bin/mysql_config' '--with-openssl=/usr/local' '--with-
 openssl-dir=/usr/local' '--with-pdo-mysql=shared' '--with-pdo-sqlite=shared'
 '--with-pgsql=/usr/local' '--with-pic' '--with-png-dir=/usr/local' '--with-
 pspell' '--with-snmp' '--with-sqlite=shared' '--with-tidy=/opt/tidy/' '--with-
 ttf' '--with-xmlrpc' '--with-xpm-dir=/usr/local' '--with-xsl=/opt/xslt/' '--
 with-zlib' '--with-zlib-dir=/usr'

 Thanks in advance,
 Szczepan Holyszewski

 --
 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] array() returns something weird

2009-08-22 Thread Szczepan Hołyszewski
 What it looks like to me is that something is causing $foo to be a
 string before the '$foo[] = bar;' line is encountered. What do you
 get if you put a gettype($foo); just before that line?

 $foo=null;
 $foo[]=bar;  // -- $foo simply becomes an array

NULL. That is the problem. I _did_ put a gettype($foo) before the actual line.

OK, here are exact four lines of my code:

$ret=array();
foreach(self::$_allowed as $r = $a)
if ($a)
$ret[]=$r;

As you can see, there is not a shred of a chance for $ret to become something 
other than empty array between initialization and the last line in the above 
snippet which causes the fatal errror. There's no __staticGet in 5.2.9, so 
self::$_allowed cannot have side effects.

Secondly, the above code starts failing after it has executed successfully 
dozens of times (and yes, the last line _does_ get executed; in fact self::
$_allowed contains configuration information that doesn't change at runtime).

Thirdly...

  The problem is not limited to one place in code, and indeed before the
  fatal caused by append-assignment I get several warnings like
  array_diff_key(): Argument #1 is not an array, where the offending
  argument receives a result of array().

 This would appear to support my suspicion, but try inserting the
 gettype($foo) (or better, var_export($foo);) just before one of the
 lines which triggers the error, and post the results.

No, I don't think it supports your suspicion. Conversely, it indicates that 
once array() returns a strangelet, it starts returning strangelets all over 
the place. Initially it only triggers warnings but eventually one of the 
returned strangelets is used in a way that triggers a fatal error.

As per your request:

//at the beginning of the script:

$GLOBALS['offending_line_execution_count']=0;

// /srv/home/[munged]/public_html/scripts/common.php line 161 and on
// instrumented as per your request:

public static function GetAllowed() {

if (debug_mode()) echo 
++$GLOBALS['offending_line_execution_count'].br/;
$ret=array();
if (debug_mode()) echo var_export($ret).br/;
foreach(self::$_allowed as $r = $a)
if ($a)
$ret[]=$r;

if (self::$_allowEmpty) $ret[]=;
return $ret;
}

Output tail:
---
28
array ( )
29
array ( )
30
array ( )
31
array ( )
32
array ( )

Warning: array_diff_key() [function.array-diff-key]: Argument #1 is not an 
array 
in /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 350

Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 351

Warning: array_merge() [function.array-merge]: Argument #2 is not an array in 
/srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 357

Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/scripts/common.php on line 28

Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/scripts/common.php on line 28

Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/scripts/common.php on line 28
33
NULL

Fatal error: [] operator not supported for strings in 
/srv/home/u80959ue/public_html/scripts/common.php on line 168
--

The warnings come from other uses of array().

But wait! There is this invocation of debug_mode() between initialization of 
$ret var_export. Let's factor it out to be safe:

$debugmode=debug_mode();
if ($debugmode) echo 
++$GLOBALS['offending_line_execution_count'].br/;
$ret=array();
if ($debugmode) echo var_export($ret).br/;

And now the output ends with:


Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/scripts/common.php on line 28
33

Fatal error: [] operator not supported for strings in 
/srv/home/u80959ue/public_html/scripts/common.php on line 169


No NULL after 33? What the heck is going on? Does array() now return something 
that var_exports to an empty string, or does it destroy local variables? Let's 
see:

if ($debugmode) echo var_export($ret).br/; else echo 
WTF?!?!?br/;

And the output:

Warning: Invalid argument supplied for foreach() in 
/srv/home/u80959ue/public_html/scripts/common.php on line 28
33
WTF?!?!?

Fatal error: [] operator not supported for strings in 
/srv/home/u80959ue/public_html/scripts/common.php on line 169
---

Indeed, the use of array(), once it starts misbehaving, wreaks havoc in the 
local scope (possibly including the 

Re: [PHP] array() returns something weird

2009-08-22 Thread Lars Torben Wilson
2009/8/22 Szczepan Hołyszewski webmas...@strefarytmu.pl:
 What it looks like to me is that something is causing $foo to be a
 string before the '$foo[] = bar;' line is encountered. What do you
 get if you put a gettype($foo); just before that line?

         $foo=null;
         $foo[]=bar;      // -- $foo simply becomes an array

 NULL. That is the problem. I _did_ put a gettype($foo) before the actual line.

 OK, here are exact four lines of my code:

        $ret=array();
        foreach(self::$_allowed as $r = $a)
                if ($a)
                        $ret[]=$r;

 As you can see, there is not a shred of a chance for $ret to become something
 other than empty array between initialization and the last line in the above
 snippet which causes the fatal errror. There's no __staticGet in 5.2.9, so
 self::$_allowed cannot have side effects.

 Secondly, the above code starts failing after it has executed successfully
 dozens of times (and yes, the last line _does_ get executed; in fact self::
 $_allowed contains configuration information that doesn't change at runtime).

 Thirdly...

  The problem is not limited to one place in code, and indeed before the
  fatal caused by append-assignment I get several warnings like
  array_diff_key(): Argument #1 is not an array, where the offending
  argument receives a result of array().

 This would appear to support my suspicion, but try inserting the
 gettype($foo) (or better, var_export($foo);) just before one of the
 lines which triggers the error, and post the results.

 No, I don't think it supports your suspicion. Conversely, it indicates that
 once array() returns a strangelet, it starts returning strangelets all over
 the place. Initially it only triggers warnings but eventually one of the
 returned strangelets is used in a way that triggers a fatal error.

 As per your request:

        //at the beginning of the script:

        $GLOBALS['offending_line_execution_count']=0;

        // /srv/home/[munged]/public_html/scripts/common.php line 161 and on
        // instrumented as per your request:

        public static function GetAllowed() {

                if (debug_mode()) echo 
 ++$GLOBALS['offending_line_execution_count'].br/;
                $ret=array();
                if (debug_mode()) echo var_export($ret).br/;
                foreach(self::$_allowed as $r = $a)
                        if ($a)
                                $ret[]=$r;

                if (self::$_allowEmpty) $ret[]=;
                return $ret;
        }

 Output tail:
 ---
 28
 array ( )
 29
 array ( )
 30
 array ( )
 31
 array ( )
 32
 array ( )

 Warning: array_diff_key() [function.array-diff-key]: Argument #1 is not an 
 array
 in /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 350

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 351

 Warning: array_merge() [function.array-merge]: Argument #2 is not an array in
 /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 357

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28
 33
 NULL

 Fatal error: [] operator not supported for strings in
 /srv/home/u80959ue/public_html/scripts/common.php on line 168
 --

 The warnings come from other uses of array().

 But wait! There is this invocation of debug_mode() between initialization of
 $ret var_export. Let's factor it out to be safe:

                $debugmode=debug_mode();
                if ($debugmode) echo 
 ++$GLOBALS['offending_line_execution_count'].br/;
                $ret=array();
                if ($debugmode) echo var_export($ret).br/;

 And now the output ends with:

 
 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28
 33

 Fatal error: [] operator not supported for strings in
 /srv/home/u80959ue/public_html/scripts/common.php on line 169
 

 No NULL after 33? What the heck is going on? Does array() now return something
 that var_exports to an empty string, or does it destroy local variables? Let's
 see:

                if ($debugmode) echo var_export($ret).br/; else echo 
 WTF?!?!?br/;

 And the output:
 
 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28
 33
 WTF?!?!?

 Fatal error: [] operator not supported for strings in
 /srv/home/u80959ue/public_html/scripts/common.php on line 169
 ---

 Indeed, the use of 

Re: [PHP] array() returns something weird

2009-08-22 Thread Ralph Deffke
well, when I saw ur post I got immediately the thought I would bed it has to
do with some stuff of $this or self.

I did play arround a bit with class creation the last days and yes, with
using self parent and $this I did put the HTTPPD in unstable and sometimes
it died without beeing able to send any error.

well this doesn't help very mutch.

I have two point:

(1)ur code is ( sorry ) lazy written, invest the brackets !! ur code writing
is predestinated for that type of error. shooting variable types arround by
pulling out of foreach loops,  if's,  is typical.

(2) using static variables are known for type missmatch errors just anything
has acces to them even if the containing class is not instantinated. many
dirty things can happen unless of corse they are not private.

further sugestions: check if you work on ur arrays with functions returning
array on success but false on fail or something like that. also a typical
source for that type of error

are u using magic __set ? I ran into a type change as well with it

good luck

ralph_def...@yahoo.de


Szczepan Holyszewski webmas...@strefarytmu.pl wrote in message
news:200908222152.55846.webmas...@strefarytmu.pl...
  What it looks like to me is that something is causing $foo to be a
  string before the '$foo[] = bar;' line is encountered. What do you
  get if you put a gettype($foo); just before that line?
 
  $foo=null;
  $foo[]=bar;  // -- $foo simply becomes an array

 NULL. That is the problem. I _did_ put a gettype($foo) before the actual
line.

 OK, here are exact four lines of my code:

 $ret=array();
 foreach(self::$_allowed as $r = $a)
 if ($a)
 $ret[]=$r;

 As you can see, there is not a shred of a chance for $ret to become
something
 other than empty array between initialization and the last line in the
above
 snippet which causes the fatal errror. There's no __staticGet in 5.2.9, so
 self::$_allowed cannot have side effects.

 Secondly, the above code starts failing after it has executed successfully
 dozens of times (and yes, the last line _does_ get executed; in fact
self::
 $_allowed contains configuration information that doesn't change at
runtime).

 Thirdly...

   The problem is not limited to one place in code, and indeed before the
   fatal caused by append-assignment I get several warnings like
   array_diff_key(): Argument #1 is not an array, where the offending
   argument receives a result of array().
 
  This would appear to support my suspicion, but try inserting the
  gettype($foo) (or better, var_export($foo);) just before one of the
  lines which triggers the error, and post the results.

 No, I don't think it supports your suspicion. Conversely, it indicates
that
 once array() returns a strangelet, it starts returning strangelets all
over
 the place. Initially it only triggers warnings but eventually one of the
 returned strangelets is used in a way that triggers a fatal error.

 As per your request:

 //at the beginning of the script:

 $GLOBALS['offending_line_execution_count']=0;

 // /srv/home/[munged]/public_html/scripts/common.php line 161 and on
 // instrumented as per your request:

 public static function GetAllowed() {

 if (debug_mode()) echo
++$GLOBALS['offending_line_execution_count'].br/;
 $ret=array();
 if (debug_mode()) echo var_export($ret).br/;
 foreach(self::$_allowed as $r = $a)
 if ($a)
 $ret[]=$r;

 if (self::$_allowEmpty) $ret[]=;
 return $ret;
 }

 Output tail:
 ---
 28
 array ( )
 29
 array ( )
 30
 array ( )
 31
 array ( )
 32
 array ( )

 Warning: array_diff_key() [function.array-diff-key]: Argument #1 is not an
array
 in /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 350

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 351

 Warning: array_merge() [function.array-merge]: Argument #2 is not an array
in
 /srv/home/u80959ue/public_html/v3/scripts/SimpliciText.php on line 357

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28

 Warning: Invalid argument supplied for foreach() in
 /srv/home/u80959ue/public_html/scripts/common.php on line 28
 33
 NULL

 Fatal error: [] operator not supported for strings in
 /srv/home/u80959ue/public_html/scripts/common.php on line 168
 --

 The warnings come from other uses of array().

 But wait! There is this invocation of debug_mode() between initialization
of
 $ret var_export. Let's factor it out to be safe:

 $debugmode=debug_mode();
 if ($debugmode) echo ++$GLOBALS['offending_line_execution_count'].br/;
 $ret=array();
 if ($debugmode) echo var_export($ret).br/;

 And now the output ends with:

 
 Warning: Invalid argument supplied for foreach() in
 

Re: [PHP] array() returns something weird

2009-08-22 Thread Szczepan Hołyszewski
 Hm. . .it does look odd. Searching the bugs database at
 http://bugs.php.net does turn up one other report (at
 http://bugs.php.net/bug.php?id=47870 ) of array() returning NULL in
 certain hard-to-duplicate circumstances on FreeBSD,

Yes, I found it even before posting here, but I wasn't sure whether to file a 
new report or comment under this one. If your intuition is that these bugs are 
related, then I will do the latter. Thank you for your attention.

 I don't suppose you have a development environment on another
 machine where you can test another version of PHP?

Assuming you mean a FreeBSD environment, nope :( but I will try on Linux 
tomorrow.

Regards,
Szczepan Holyszewski


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



Re: [PHP] array() returns something weird

2009-08-22 Thread Lars Torben Wilson
2009/8/22 Szczepan Hołyszewski webmas...@strefarytmu.pl:
 Hm. . .it does look odd. Searching the bugs database at
 http://bugs.php.net does turn up one other report (at
 http://bugs.php.net/bug.php?id=47870 ) of array() returning NULL in
 certain hard-to-duplicate circumstances on FreeBSD,

 Yes, I found it even before posting here, but I wasn't sure whether to file a
 new report or comment under this one. If your intuition is that these bugs are
 related, then I will do the latter. Thank you for your attention.

Well, the only things I'm basing my suspicion on are the nature of the
problem, the OS similarity and the fact that it seems to be difficult
to reproduce the problem reliably. The major problem with this guess
is that the original bug report does state that the bug did not show
up under 5.2.

 I don't suppose you have a development environment on another
 machine where you can test another version of PHP?

 Assuming you mean a FreeBSD environment, nope :( but I will try on Linux
 tomorrow.

OK. I do think (as I'm sure you know) that the best test would be in a
matching environment (since the result was reported to be different
under Linux for that bug), but of course that's not always realistic.

 Regards,
 Szczepan Holyszewski

I hope your problem can be resolved. If it does turn out to be a bug
in PHP I hope that will be enough to convince your host to upgrade.


Regards,

Torben

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



[PHP] Array

2009-08-10 Thread Ron Piggott
How do I change this ELSEIF into an array?

} elseif ( ( $page   ) AND ( $page  home_page ) AND ( $page  
verse_of_the_day_activate ) AND ( $page  member_services ) AND ( $page  
member_services_login ) AND ( $page  member_services_logoff ) AND ( $page 
 resource_center ) AND ( $page  network ) ) {

Re: [PHP] Array

2009-08-10 Thread Jonathan Tapicer
On Mon, Aug 10, 2009 at 9:28 AM, Ron
Piggottron.pigg...@actsministries.org wrote:
 How do I change this ELSEIF into an array?

 } elseif ( ( $page   ) AND ( $page  home_page ) AND ( $page  
 verse_of_the_day_activate ) AND ( $page  member_services ) AND ( $page 
  member_services_login ) AND ( $page  member_services_logoff ) AND ( 
 $page  resource_center ) AND ( $page  network ) ) {

Something like:

} elseif (!in_array($page, array(, home_page,
verse_of_the_day_activate, ...))) {

should work.

Regards,

Jonathan

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



Re: [PHP] Array

2009-08-10 Thread Robert Cummings

Ron Piggott wrote:

How do I change this ELSEIF into an array?

} elseif ( ( $page   ) AND ( $page  home_page ) AND ( $page  verse_of_the_day_activate ) AND ( $page  member_services ) AND ( 
$page  member_services_login ) AND ( $page  member_services_logoff ) AND ( $page  resource_center ) AND ( $page  network ) ) {


Put all the compared values into an array, then check that $page is not 
in_array().


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] Array

2009-08-10 Thread Jim Lucas
Ron Piggott wrote:
 How do I change this ELSEIF into an array?
 
 } elseif ( ( $page   ) AND ( $page  home_page ) AND ( $page  
 verse_of_the_day_activate ) AND ( $page  member_services ) AND ( $page 
  member_services_login ) AND ( $page  member_services_logoff ) AND ( 
 $page  resource_center ) AND ( $page  network ) ) {

?php

$d = array(
home_page,
member_services,
member_services_login,
network,
resource_center,
verse_of_the_day_activate,
);

} elseif ( !empty($page)  in_array($page, $d) ) {

?


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



[PHP] array manipulation

2009-04-16 Thread PJ
The more I get into arrays, the less I understand.
I have a ridiculously simple task which excapes me completely.
I need to ouput all fields in 1 column from 1 table in two phases sorted
alphabetically.
So, I have the query, I have the results. But since I need to split the
list into 2 parts, I need indexes. I cannot use the table index as it
does not correspond to the alphabetical order of the data column. In
order to get the index, I sort the resulting array and that now gives me
34 arrays each containing an array of my results. Wonderful!
But how do I now extract the arrays from the array?

Here is what I'm trying to do:

$SQL = SELECT category
FROM categories
ORDER BY category ASC
;
$category = array();
if ( ( $results = mysql_query($SQL, $db) ) !== false ) {
while ( $row = mysql_fetch_assoc($results) ) {
$category[$row['category']] = $row;
}
sort($category);
//var_dump($category);
echo table ;
$count = mysql_num_rows($results);
$lastIndex = $count/2 -1; echo $lastIndex;
$ii = 0;
$cat = '';
//print_r($category['0']['category']);
foreach($category as $index = $value) {
$ii++;
if ($ii != $lastIndex) {
$cat .= $value, ;
}
else {
$cat .=   $valuebr /;
}
$catn = preg_replace(/[^a-zA-Z0-9]/, , $cat);
//echo pre$category/pre;
echo tr
tda href='../categories/, $catn, .php', $cat, /a
/td
/tr ;
}
}
echo /table;

What should I be using in the foreach line?
Please help!

-- 
unheralded genius: A clean desk is the sign of a dull mind. 
-
Phil Jourdan --- p...@ptahhotep.com
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


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



Re: [PHP] array manipulation

2009-04-16 Thread PJ
Sorry, bout that.
My brain wasn't working right.
It was a lot simpler than I thought. Forget the foreach.
I used a counter. :-[

PJ wrote:
 The more I get into arrays, the less I understand.
 I have a ridiculously simple task which excapes me completely.
 I need to ouput all fields in 1 column from 1 table in two phases sorted
 alphabetically.
 So, I have the query, I have the results. But since I need to split the
 list into 2 parts, I need indexes. I cannot use the table index as it
 does not correspond to the alphabetical order of the data column. In
 order to get the index, I sort the resulting array and that now gives me
 34 arrays each containing an array of my results. Wonderful!
 But how do I now extract the arrays from the array?

 Here is what I'm trying to do:

 $SQL = SELECT category
 FROM categories
 ORDER BY category ASC
 ;
 $category = array();
 if ( ( $results = mysql_query($SQL, $db) ) !== false ) {
 while ( $row = mysql_fetch_assoc($results) ) {
 $category[$row['category']] = $row;
 }
 sort($category);
 //var_dump($category);
 echo table ;
 $count = mysql_num_rows($results);
 $lastIndex = $count/2 -1; echo $lastIndex;
 $ii = 0;
 $cat = '';
 //print_r($category['0']['category']);
 foreach($category as $index = $value) {
 $ii++;
 if ($ii != $lastIndex) {
 $cat .= $value, ;
 }
 else {
 $cat .=   $valuebr /;
 }
 $catn = preg_replace(/[^a-zA-Z0-9]/, , $cat);
 //echo pre$category/pre;
 echo tr
 tda href='../categories/, $catn, .php', $cat, /a
 /td
 /tr ;
 }
 }
 echo /table;

 What should I be using in the foreach line?
 Please help!

   


-- 
unheralded genius: A clean desk is the sign of a dull mind. 
-
Phil Jourdan --- p...@ptahhotep.com
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


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



Re: [PHP] array manipulation

2009-04-16 Thread German Geek
soln: YOU NEED A 2 WEEK HOLLIDAY at least! You need to learn to say no.
Tim-Hinnerk Heuer

http://www.ihostnz.com
Samuel Goldwynhttp://www.brainyquote.com/quotes/authors/s/samuel_goldwyn.html
- A wide screen just makes a bad film twice as bad.

2009/4/17 PJ af.gour...@videotron.ca

 The more I get into arrays, the less I understand.
 I have a ridiculously simple task which excapes me completely.
 I need to ouput all fields in 1 column from 1 table in two phases sorted
 alphabetically.
 So, I have the query, I have the results. But since I need to split the
 list into 2 parts, I need indexes. I cannot use the table index as it
 does not correspond to the alphabetical order of the data column. In
 order to get the index, I sort the resulting array and that now gives me
 34 arrays each containing an array of my results. Wonderful!
 But how do I now extract the arrays from the array?

 Here is what I'm trying to do:

 $SQL = SELECT category
FROM categories
ORDER BY category ASC
;
 $category = array();
 if ( ( $results = mysql_query($SQL, $db) ) !== false ) {
while ( $row = mysql_fetch_assoc($results) ) {
$category[$row['category']] = $row;
}
sort($category);
//var_dump($category);
echo table ;
$count = mysql_num_rows($results);
$lastIndex = $count/2 -1; echo $lastIndex;
$ii = 0;
$cat = '';
 //print_r($category['0']['category']);
foreach($category as $index = $value) {
$ii++;
if ($ii != $lastIndex) {
$cat .= $value, ;
}
else {
$cat .=   $valuebr /;
}
$catn = preg_replace(/[^a-zA-Z0-9]/, , $cat);
//echo pre$category/pre;
echo tr
tda href='../categories/, $catn, .php', $cat, /a
/td
/tr ;
}
 }
 echo /table;

 What should I be using in the foreach line?
 Please help!

 --
 unheralded genius: A clean desk is the sign of a dull mind. 
 -
 Phil Jourdan --- p...@ptahhotep.com
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


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




[PHP] Hello, I have a question about php array max number

2009-04-09 Thread PeterDu

Hello,

I have an array including 2000 records in database,

but when fetch all of them, why just get 1500 records? 



Does that depend on my computer?

Peter

__ Information from ESET NOD32 Antivirus, version of virus signature 
database 3997 (20090409) __

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com




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



[PHP] Hello, I have a question about php array max number

2009-04-09 Thread PeterDu

Hello,

I have an array including 2000 records in database,

but when fetch all of them, why just get 1500 records? 



Does that depend on my computer?

Peter

__ Information from ESET NOD32 Antivirus, version of virus signature 
database 3997 (20090409) __

The message was checked by ESET NOD32 Antivirus.

http://www.eset.com




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



Re: [PHP] Hello, I have a question about php array max number

2009-04-09 Thread Bastien Koert
On Thu, Apr 9, 2009 at 2:36 PM, PeterDu pete...@telus.net wrote:

 Hello,

 I have an array including 2000 records in database,

 but when fetch all of them, why just get 1500 records?

 Does that depend on my computer?

 Peter

 __ Information from ESET NOD32 Antivirus, version of virus
 signature database 3997 (20090409) __

 The message was checked by ESET NOD32 Antivirus.

 http://www.eset.com




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



Could be the memory limit on the server, could be the query only returning
1500 rows.

-- 

Bastien

Cat, the other other white meat


[PHP] Re: Hello, I have a question about php array max number

2009-04-09 Thread Jonesy
On Thu, 9 Apr 2009 10:08:12 -0700, PeterDu wrote:
 Hello,

 I have an array including 2000 records in database,

 but when fetch all of them, why just get 1500 records? 

 Does that depend on my computer?

Well, at least you hi-jacked a thread that did not pertain to PHP and 
put it back On Topic!



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



[PHP] Array Brain Freeze

2009-03-19 Thread Dan Shirah
Hello all,

I have the follwoing piece of code:

//reference a stored procedure
$procedure = Execute Procedure informix.arrest_char($part_id);

//run the stored procedure
$char_query = ifx_query($procedure, $connect_id);

//get the result of the stored procedure
$char_result = ifx_fetch_row($char_query);

//print out the returned values.
print_r($char_result);

This all works just fine and I have values returned.  What I am trying to do
is assign one of the array items to a variable.

In the past I have done so like this:

$stat_1 = $char_result['stat_1'];

But for some odd reason $stat_1 doesn't contain anything.

Am I going crazy or am I doing something wrong?

Thanks,

Dan


[PHP] array/iteration issue!!

2008-11-27 Thread bruce
hi.

i have the following test multidiminsional array. i'm trying to figure out
how to iterate through the array, to produce something like

foo, physics, sss
foo, physics, sffgg
foo, english, sss
foo, english, sffgg

can't quite seem to get it right!!

thoughts/comments... etc...

thanks


$a=array(college= foo,
 dept=array(dept= physics,
  class=array(class1=sss,class2=sffgg)
),
dept=array(dept= english,
class=array(class1=sss,class2=sffgg)
)
);


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



Re: [PHP] array/iteration issue!!

2008-11-27 Thread Robert Cummings
On Thu, 2008-11-27 at 17:31 -0800, bruce wrote:
 hi.
 
 i have the following test multidiminsional array. i'm trying to figure out
 how to iterate through the array, to produce something like
 
 foo, physics, sss
 foo, physics, sffgg
 foo, english, sss
 foo, english, sffgg
 
 can't quite seem to get it right!!
 
 thoughts/comments... etc...
 
 thanks
 
 
 $a=array(college= foo,
dept=array(dept= physics,
   class=array(class1=sss,class2=sffgg)
   ),
   dept=array(dept= english,
 class=array(class1=sss,class2=sffgg)
 )
   );

You can't. You're array is valid but the second 'dept' key overwrites
the first. Thus the physics dept is lost.

Check it for yourself... print_r( $a )

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] array/iteration issue!!

2008-11-27 Thread bruce
hey robert..

ok.. so if i changed the array to have a dept1, and a dept2

$a=array(college= foo,
 dept1=array(dept= physics,
  class=array(class1=sss,class2=sffgg)
),
dept2=array(dept= english,
class=array(class1=sss,class2=sffgg)
)
);
how would i iterate through this..??

thanks


-Original Message-
From: Robert Cummings [mailto:[EMAIL PROTECTED]
Sent: Thursday, November 27, 2008 6:18 PM
To: bruce
Cc: 'PHP General list'
Subject: Re: [PHP] array/iteration issue!!


On Thu, 2008-11-27 at 17:31 -0800, bruce wrote:
 hi.

 i have the following test multidiminsional array. i'm trying to figure out
 how to iterate through the array, to produce something like

 foo, physics, sss
 foo, physics, sffgg
 foo, english, sss
 foo, english, sffgg

 can't quite seem to get it right!!

 thoughts/comments... etc...

 thanks

 
 $a=array(college= foo,
dept=array(dept= physics,
   class=array(class1=sss,class2=sffgg)
   ),
   dept=array(dept= english,
 class=array(class1=sss,class2=sffgg)
 )
   );

You can't. You're array is valid but the second 'dept' key overwrites
the first. Thus the physics dept is lost.

Check it for yourself... print_r( $a )

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


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



RE: [PHP] array/iteration issue!!

2008-11-27 Thread Robert Cummings
On Thu, 2008-11-27 at 18:55 -0800, bruce wrote:
 hey robert..
 
 ok.. so if i changed the array to have a dept1, and a dept2
 
 $a=array(college= foo,
dept1=array(dept= physics,
   class=array(class1=sss,class2=sffgg)
   ),
   dept2=array(dept= english,
 class=array(class1=sss,class2=sffgg)
 )
   );
 how would i iterate through this..??

Your array is terribly structured. But the following provides traversal
in the way you want:

?php

$a = array
(
college = foo,
dept1   = array
(
dept  = physics,
class = array
(
class1 = sss,
class2 = sffgg
)
),
dept2 = array
(
dept  = english,
class = array
(
class1 = sss,
class2 = sffgg
)
)
);

$college = $a['college'];
foreach( $a as $deptKey = $deptInfo )
{
if( strpos( $deptKey, 'dept' ) === 0 )
{
$dept = $deptInfo['dept'];
foreach( $deptInfo['class'] as $class )
{
echo $college, $dept, $class\n;
}
}
}

?

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] array/iteration issue!!

2008-11-27 Thread bruce
hey robert!!

thanks. and yeah, you're right, it's not the best.. so tell me, given that
i'm ripping through this on the fly, and i can have the structure in any way
i choose. this is just to simulate/populate some test tbls.. what's a better
way to create an array structure to have a collegename, followed by some
deptnames, followed by some classnames for the depts...

perhaps something like this??

$a = array
(
college = foo,
array
(
dept  = physics,
class = array
(
class1 = sss,
class2 = sffgg
)
),
array
(
dept  = english,
class = array
(
class1 = sss,
class2 = sffgg
)
)
);


-Original Message-
From: Robert Cummings [mailto:[EMAIL PROTECTED]
Sent: Thursday, November 27, 2008 7:10 PM
To: bruce
Cc: 'PHP General list'
Subject: RE: [PHP] array/iteration issue!!


On Thu, 2008-11-27 at 18:55 -0800, bruce wrote:
 hey robert..

 ok.. so if i changed the array to have a dept1, and a dept2

 $a=array(college= foo,
dept1=array(dept= physics,
   class=array(class1=sss,class2=sffgg)
   ),
   dept2=array(dept= english,
 class=array(class1=sss,class2=sffgg)
 )
   );
 how would i iterate through this..??

Your array is terribly structured. But the following provides traversal
in the way you want:

?php

$a = array
(
college = foo,
dept1   = array
(
dept  = physics,
class = array
(
class1 = sss,
class2 = sffgg
)
),
dept2 = array
(
dept  = english,
class = array
(
class1 = sss,
class2 = sffgg
)
)
);

$college = $a['college'];
foreach( $a as $deptKey = $deptInfo )
{
if( strpos( $deptKey, 'dept' ) === 0 )
{
$dept = $deptInfo['dept'];
foreach( $deptInfo['class'] as $class )
{
echo $college, $dept, $class\n;
}
}
}

?

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] array/iteration issue!!

2008-11-27 Thread Robert Cummings
On Thu, 2008-11-27 at 19:36 -0800, bruce wrote:
 hey robert!!
 
 thanks. and yeah, you're right, it's not the best.. so tell me, given that
 i'm ripping through this on the fly, and i can have the structure in any way
 i choose. this is just to simulate/populate some test tbls.. what's a better
 way to create an array structure to have a collegename, followed by some
 deptnames, followed by some classnames for the depts...
 
 perhaps something like this??
 
 $a = array
 (
 college = foo,
 array
 (
 dept  = physics,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 ),
 array
 (
 dept  = english,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 )
 );

Not quite. The following is probably what you want:

?php

$colleges = array
(
array
(
'name'  = 'Blah Blah University',
'depts' = array
(
array
(
'name'= 'physics',
'classes' = array
(
'sss',
'sffgg',
),
),
array
(
'name'= 'english',
'classes' = array
(
'sss',
'sffgg',
),
),
),
),
array
(
'name'  = 'Glah Gleh University',
'depts' = array
(
array
(
'name'= 'physics',
'classes' = array
(
'sss',
'sffgg',
),
),
array
(
'name'= 'english',
'classes' = array
(
'sss',
'sffgg',
),
),
),
),
);

foreach( $colleges as $college )
{
$collegeName = $college['name'];
foreach( $college['depts'] as $dept )
{
$deptName = $dept['name'];
foreach( $dept['classes'] as $className )
{
echo $collegeName, $deptName, $className\n;
}
}
}

?

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] array/iteration issue!!

2008-11-27 Thread Micah Gersten
Robert Cummings wrote:
 On Thu, 2008-11-27 at 19:36 -0800, bruce wrote:
   
 hey robert!!

 thanks. and yeah, you're right, it's not the best.. so tell me, given that
 i'm ripping through this on the fly, and i can have the structure in any way
 i choose. this is just to simulate/populate some test tbls.. what's a better
 way to create an array structure to have a collegename, followed by some
 deptnames, followed by some classnames for the depts...

 perhaps something like this??

 $a = array
 (
 college = foo,
 array
 (
 dept  = physics,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 ),
 array
 (
 dept  = english,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 )
 );
 

 Not quite. The following is probably what you want:

 ?php

 $colleges = array
 (
 array
 (
 'name'  = 'Blah Blah University',
 'depts' = array
 (
 array
 (
 'name'= 'physics',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 array
 (
 'name'= 'english',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 ),
 ),
 array
 (
 'name'  = 'Glah Gleh University',
 'depts' = array
 (
 array
 (
 'name'= 'physics',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 array
 (
 'name'= 'english',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 ),
 ),
 );

 foreach( $colleges as $college )
 {
 $collegeName = $college['name'];
 foreach( $college['depts'] as $dept )
 {
 $deptName = $dept['name'];
 foreach( $dept['classes'] as $className )
 {
 echo $collegeName, $deptName, $className\n;
 }
 }
 }

 ?

 Cheers,
 Rob.
   
This is actually a much smaller data structure.

$colleges = array
(
'Blah Blah University' =
array
(
'physics' = array
(
'sss',
'sffgg',
),
'english' = array
(
'sss',
'sffgg',
)
),
'Glah Gleh University' =
array
(
'physics' = array
(
'sss',
'sffgg',
),
'english' = array
(
'sss',
'sffgg',
),
)
 );


foreach( $colleges as $collegeName = $depts )
{
 foreach( $depts as $deptName = $classes)
{
foreach( $classes as $className )
{
echo $collegeName, $deptName, $className\n;
}
}
}


Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com





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



RE: [PHP] array/iteration issue!!

2008-11-27 Thread bruce
much props guys!!!

thanks!!


-Original Message-
From: Micah Gersten [mailto:[EMAIL PROTECTED]
Sent: Thursday, November 27, 2008 8:23 PM
To: Robert Cummings
Cc: bruce; 'PHP General list'
Subject: Re: [PHP] array/iteration issue!!


Robert Cummings wrote:
 On Thu, 2008-11-27 at 19:36 -0800, bruce wrote:

 hey robert!!

 thanks. and yeah, you're right, it's not the best.. so tell me, given
that
 i'm ripping through this on the fly, and i can have the structure in any
way
 i choose. this is just to simulate/populate some test tbls.. what's a
better
 way to create an array structure to have a collegename, followed by some
 deptnames, followed by some classnames for the depts...

 perhaps something like this??

 $a = array
 (
 college = foo,
 array
 (
 dept  = physics,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 ),
 array
 (
 dept  = english,
 class = array
 (
 class1 = sss,
 class2 = sffgg
 )
 )
 );


 Not quite. The following is probably what you want:

 ?php

 $colleges = array
 (
 array
 (
 'name'  = 'Blah Blah University',
 'depts' = array
 (
 array
 (
 'name'= 'physics',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 array
 (
 'name'= 'english',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 ),
 ),
 array
 (
 'name'  = 'Glah Gleh University',
 'depts' = array
 (
 array
 (
 'name'= 'physics',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 array
 (
 'name'= 'english',
 'classes' = array
 (
 'sss',
 'sffgg',
 ),
 ),
 ),
 ),
 );

 foreach( $colleges as $college )
 {
 $collegeName = $college['name'];
 foreach( $college['depts'] as $dept )
 {
 $deptName = $dept['name'];
 foreach( $dept['classes'] as $className )
 {
 echo $collegeName, $deptName, $className\n;
 }
 }
 }

 ?

 Cheers,
 Rob.

This is actually a much smaller data structure.

$colleges = array
(
'Blah Blah University' =
array
(
'physics' = array
(
'sss',
'sffgg',
),
'english' = array
(
'sss',
'sffgg',
)
),
'Glah Gleh University' =
array
(
'physics' = array
(
'sss',
'sffgg',
),
'english' = array
(
'sss',
'sffgg',
),
)
 );


foreach( $colleges as $collegeName = $depts )
{
 foreach( $depts as $deptName = $classes)
{
foreach( $classes as $className )
{
echo $collegeName, $deptName, $className\n;
}
}
}


Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.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] array/iteration issue!!

2008-11-27 Thread Robert Cummings
On Thu, 2008-11-27 at 22:22 -0600, Micah Gersten wrote:

 This is actually a much smaller data structure.
 
 $colleges = array
 (
   'Blah Blah University' =
 array
 (
 'physics' = array
 (
 'sss',
 'sffgg',
 ),
 'english' = array
 (
 'sss',
 'sffgg',
 )
   ),
   'Glah Gleh University' =
 array
 (
 'physics' = array
 (
 'sss',
 'sffgg',
 ),
 'english' = array
 (
 'sss',
 'sffgg',
 ),
 )
  );
 
 
 foreach( $colleges as $collegeName = $depts )
 {
  foreach( $depts as $deptName = $classes)
 {
 foreach( $classes as $className )
 {
 echo $collegeName, $deptName, $className\n;
 }
 }
 }

Yes, I thought of that one too, but it's less flexible. What if you need
to add other fields to the college, or department. Then you'd need to
redo the whole structure to something more similar to what I did. Since
bruce was having issues, I gave him a flexible format that could handle
other fields if they arose.

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] array/iteration issue!!

2008-11-27 Thread bruce
both ways work...!!!

this is a really simple/quick issue to populate some test db tbls.. i've
only played with multi php arrays (sp??) in passing... and my days of being
a serious eng/software guy are long over!!

although.. with this economy!

thanks




-Original Message-
From: Robert Cummings [mailto:[EMAIL PROTECTED]
Sent: Thursday, November 27, 2008 8:40 PM
To: Micah Gersten
Cc: bruce; 'PHP General list'
Subject: Re: [PHP] array/iteration issue!!


On Thu, 2008-11-27 at 22:22 -0600, Micah Gersten wrote:

 This is actually a much smaller data structure.

 $colleges = array
 (
   'Blah Blah University' =
 array
 (
 'physics' = array
 (
 'sss',
 'sffgg',
 ),
 'english' = array
 (
 'sss',
 'sffgg',
 )
   ),
   'Glah Gleh University' =
 array
 (
 'physics' = array
 (
 'sss',
 'sffgg',
 ),
 'english' = array
 (
 'sss',
 'sffgg',
 ),
 )
  );


 foreach( $colleges as $collegeName = $depts )
 {
  foreach( $depts as $deptName = $classes)
 {
 foreach( $classes as $className )
 {
 echo $collegeName, $deptName, $className\n;
 }
 }
 }

Yes, I thought of that one too, but it's less flexible. What if you need
to add other fields to the college, or department. Then you'd need to
redo the whole structure to something more similar to what I did. Since
bruce was having issues, I gave him a flexible format that could handle
other fields if they arose.

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


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



[PHP] Array of PDO objects

2008-06-06 Thread Miguel J. Jiménez
Hi, I want to know if I can set an array with PDO objects, thus:

$foo = array(new PDO(...), new PDO(...));
$oSt = $foo[0]-prepare(...);

and so on... I tried that aproach and PHP is always complaining about
using prepare() in a non-object...

---
.-.
| Miguel J. Jiménez   |
| Sector Público, ISOTROL S.A.|
| [EMAIL PROTECTED]   |
:-:
| KeyID 0xFFE63EC6 hkp://pgp.rediris.es:11371 |
:-:
| Edificio BLUENET, Avda. Isaac Newton nº3, 4ª planta.|
| Parque Tecnológico Cartuja '93, 41092 Sevilla (ESP).|
| Tlfn: +34 955 036 800 (ext.1805) - Fax: +34 955 036 849 |
| http://www.isotrol.com  |
:-:
| UTM ED-50 X:765205.09 Y:4144614.91 Huso: 29 |
:-:
|   Me dijeron: 'instala Windows, se listo'; así que |
| instalé primero Windows y luego fui listo y lo borré|
| para instalar Linux|
'-'


signature.asc
Description: PGP signature


Re: [PHP] Array of PDO objects

2008-06-06 Thread Nathan Nobbe
2008/6/6 Miguel J. Jiménez [EMAIL PROTECTED]:

 Hi, I want to know if I can set an array with PDO objects, thus:

$foo = array(new PDO(...), new PDO(...));
$oSt = $foo[0]-prepare(...);

 and so on... I tried that aproach and PHP is always complaining about
 using prepare() in a non-object...


i doubt it has anything to do w/ PDO.  have you tried var_dump() to inspect
the contents of $foo[0] ?  and also, have you tried creating the PDO
instances w/ the same arguments outside of the array construct to determine
if there is any difference?

-nathan


RE: [PHP] array recursion from database rows

2008-05-25 Thread Wolf
Bob,  

Post your failing code and we'l be glad to give you pointers on fixing it.  
This list doesn't exist to write code for you (unless your dropping coin into 
our paypal account) but all of us are willing to help with posted code.

Wolf

-Original Message-
From: Bob [EMAIL PROTECTED]
Sent: Saturday, May 24, 2008 2:25 PM
To: php-general@lists.php.net
Subject: [PHP] array recursion from database rows

Hi.

I have a database table I have created for navigation.

The table fields are uid, parent_id, menu_name.

Each entry is either a top level element with a parent_id of 0 or a child
which has a parent_id that relates to the parent uid.

What I am trying to do is recurse through a set of rows adding the
child(ren) of a parent to a multi-dimensional array.

Does anyone know how I can do this, I've tried (unsuccessfully) to traverse
the rows to create this array but I keep failing miserably.

This is probably very easy for the people on this list so I am hoping
someone could help me out.

Thanks in advance.

Cheers.

Bob


-- 


[The entire original message is not included]


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



[PHP] array recursion from database rows

2008-05-24 Thread Bob
Hi.

I have a database table I have created for navigation.

The table fields are uid, parent_id, menu_name.

Each entry is either a top level element with a parent_id of 0 or a child
which has a parent_id that relates to the parent uid.

What I am trying to do is recurse through a set of rows adding the
child(ren) of a parent to a multi-dimensional array.

Does anyone know how I can do this, I've tried (unsuccessfully) to traverse
the rows to create this array but I keep failing miserably.

This is probably very easy for the people on this list so I am hoping
someone could help me out.

Thanks in advance.

Cheers.

Bob


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



Re: [PHP] array recursion from database rows

2008-05-24 Thread Bastien Koert
On 5/24/08, Bob [EMAIL PROTECTED] wrote:

 Hi.

 I have a database table I have created for navigation.

 The table fields are uid, parent_id, menu_name.

 Each entry is either a top level element with a parent_id of 0 or a child
 which has a parent_id that relates to the parent uid.

 What I am trying to do is recurse through a set of rows adding the
 child(ren) of a parent to a multi-dimensional array.

 Does anyone know how I can do this, I've tried (unsuccessfully) to traverse
 the rows to create this array but I keep failing miserably.

 This is probably very easy for the people on this list so I am hoping
 someone could help me out.

 Thanks in advance.

 Cheers.

 Bob



if you order your result set by record id and parent id

then your set should be much easier to loop thru, when you hit an empty
parent id field its a new parent and you could use the row id (or whaever)
as the key and then keep adding the children until you hit a new (empty)
parent id




-- 

 Bastien

 Cat, the other other white meat


Re: [PHP] Array pointer to a function

2008-04-07 Thread Nathan Nobbe
On Tue, Apr 8, 2008 at 12:00 AM, hce [EMAIL PROTECTED] wrote:

 Hi,

 Is it possible for an array to point a function:

 Asignmanet

 $ArrayPointer = $this-MyFunction;

 Invoke:

 $ArraryPointer();


i would recommend you investigate variable functions

1.  http://www.php.net/manual/en/functions.variable-functions.php

so you dont exactly get functional language behavior; but you can 'pass
around a function'.  so for example; if you have
?php
function someFunc() {}
/**
 * then you can pass around strings that refer to it; as in
 */
$someFuncPointer = 'someFunc';

/**
 * then you can call it using the variable function construct; as in
 */
$someFuncPointer();  // invoking someFunc()
?

you can pass parameters to such an invocation; as in
?php
$someFuncPointer(1, $b, $yaddaYadda);
?

and it works for object instances
?php
class MyClass { function doStuff() {} }
$b = new MyClass();
$b-doStuff();
?

and it works for static object method calls
?php
class OtherClass { static function doMoreStuff() {} }
$b = 'doMoreStuff';
?

you can also store the class name or instance in variables and it still
works.  here the output of a little php -a session

?php
class M { static function b() {} function n() {} }
$m = 'M';
$b = 'b';
$m::$b();
$n = new M();
$n-b();
$n-$b();
?

and thats just the tip of the iceberg!  there is also the php psuedo type
callback; and there are some other functions that are pertinent.
call_user_func();  // very similar to variable functions
call_user_func_array()

-nathan


Re: [PHP] Array pointer to a function

2008-04-07 Thread Robert Cummings

On Tue, 2008-04-08 at 14:00 +1000, hce wrote:
 Hi,
 
 Is it possible for an array to point a function:
 
 Asignmanet
 
 $ArrayPointer = $this-MyFunction;
 
 Invoke:
 
 $ArraryPointer();

No, you can't do what you've done above. What you can do is...

?php

$ptr = array( 'obj' = $this, 'method' = 'MyFunction' );
$ptr['obj']-$ptr['method']();

?

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



[PHP] PHP: array with null shows different with print_r and var_dump

2008-04-02 Thread Sanjay Mantoor
Hello,

I am new to PHP and PHP community.

Following program outputs different values with print_r and var_dump.

$array = array(null, NULL);

print_r($array); prints values like below
Array
(
[0] =
[1] =
)

where as var_dump($array) prints values like below
array(2) {
  [0]=
  NULL// Does this convert to null to NULL?
  [1]=
  NULL
}

Can you tell me why the above difference?


-- 
Thanks,
Sanjay Mantoor


Re: [PHP] PHP: array with null shows different with print_r and var_dump

2008-04-02 Thread Casey
On Tue, Apr 1, 2008 at 11:49 PM, Sanjay Mantoor
[EMAIL PROTECTED] wrote:
 Hello,

  I am new to PHP and PHP community.

  Following program outputs different values with print_r and var_dump.

  $array = array(null, NULL);

  print_r($array); prints values like below
  Array
  (
 [0] =
 [1] =
  )

print_r converts null, which is a variable type, like integer, string,
float, etc, into an empty string.
  where as var_dump($array) prints values like below
  array(2) {
   [0]=
   NULL// Does this convert to null to NULL?
null is case-insensitive, so it doesn't matter how you type it.
   [1]=
   NULL
  }
var_dump converts null into the string NULL.

  Can you tell me why the above difference?



-- 
-Casey

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



<    1   2   3   4   5   6   7   8   9   10   >