Page 1 of 1

Cannot create a new array key index

Posted: Wed Apr 04, 2007 12:57 pm
by jayreed21
I am using the following code to iterate through a list of items:

Code: Select all

foreach ( $Cart["cart_content"] as $item)
		{
		$customerID = $item["customerID"];
  		if ($customerID == 0)
    		{
           $sellerName="Company";
        }
  		else
    		{
    		   $sellerName= getSellerNameFromID($customerID);
    		}
    $item["seller"]= $sellerName;
		}
Is there any reason why the sellerNames would not get added to $Cart["cart_content"]["seller"]?

THanks

Posted: Wed Apr 04, 2007 1:48 pm
by Mordred
$item is just a copy. You need (works for both php4 and php5):

Code: Select all

foreach ( $Cart["cart_content"] as $key=>$item)
...
//$item["seller"]= $sellerName; -- no
$Cart['cart_content'][$key]['seller'] = $sellerName;
Learn to use single quotes whenever possible btw ;)

Posted: Thu Apr 05, 2007 8:24 am
by jayreed21
Thanks Mordred,

That got it. I am not sure why, but the foreach loop has always been confusing to me. I do like using them better than for loops for messing with arrays.

Cheers!


J

Posted: Thu Apr 05, 2007 8:33 am
by mentor
Mordred wrote:Learn to use single quotes whenever possible btw ;)
what does that mean?

Posted: Thu Apr 05, 2007 8:38 am
by Mordred
mentor wrote:
Mordred wrote:Learn to use single quotes whenever possible btw ;)
what does that mean?
If you won't use variable substitution ("This $var will be substituted"), it is good to 'train' yourself to use single quotes: 'Single quotes for static strings'. It is by no means fatal to use double quotes, but there is significant performance gain in single quotes, if such things matter to you.

Posted: Thu Apr 05, 2007 10:20 am
by stereofrog
Mordred wrote:It is by no means fatal to use double quotes, but there is significant performance gain in single quotes, if such things matter to you.
This was correct years ago (although the "performance gain" never was "significant"), modern versions of php generate exactly the same opcode for echo 'XYZ' and echo "XYZ".

Posted: Fri Apr 06, 2007 3:06 am
by Mordred
Oops, my bad, I apologise.

stereofrog is correct, for simple strings single and double quotes behave with an insignificant difference.
http://www.php.lt/benchmark/phpbench.php

I was left with the (wrong) impression that the php parser is used for double-quoted strings, while apparently this is done only if the string contains unescaped $-s.