Re: [PHP] Arrays
On Mon, Feb 25, 2013 at 9:51 PM, Karl DeSaulniers k...@designdrumm.com wrote: Never mind. I found a different function that reads out the children as well into the array. function xml_parse_into_assoc($data) { $p = xml_parser_create(); xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($p, $data, $vals, $index); xml_parser_free($p); $levels = array(null); foreach ($vals as $val) { if ($val['type'] == 'open' || $val['type'] == 'complete') { if (!array_key_exists($val['level'], $levels)) { $levels[$val['level']] = array(); } } $prevLevel = $levels[$val['level'] - 1]; $parent = $prevLevel[sizeof($prevLevel)-1]; if ($val['type'] == 'open') { $val['children'] = array(); array_push($levels[$val['level']], $val); continue; } else if ($val['type'] == 'complete') { $parent['children'][$val['tag']] = $val['value']; } else if ($val['type'] == 'close') { $pop = array_pop($levels[$val['level']]); $tag = $pop['tag']; if ($parent) { if (!array_key_exists($tag, $parent['children'])) { $parent['children'][$tag] = $pop['children']; } else if (is_array($parent['children'][$tag])) { if(!isset($parent['children'][$tag][0])) { $oldSingle = $parent['children'][$tag]; $parent['children'][$tag] = null; $parent['children'][$tag][] = $oldSingle; } $parent['children'][$tag][] = $pop['children']; } } else { return(array($pop['tag'] = $pop['children'])); } } $prevLevel[sizeof($prevLevel)-1] = $parent; } } $params = xml_parse_into_assoc($result);//$result = xml result from USPS api Original function by: jemptymethod at gmail dot com Duplicate names fix by: Anonymous (comment right above original function) Best, Karl On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote: On 02/25/2013 05:40 PM, Karl DeSaulniers wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com This will never work. Your last array will always overwrite your previous array. Here is how I would suggest building it: $items = array( 1 = array( serviceid = 1, servicename= signature required, price = $4.95 ), 15 = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) This will ensure that your first level indexes never overwrite themselves. But, with that change made, then do this: foreach ( $items AS $item ) { if ( array_key_exists('price', $item) ) { echo $item['price']; } else { echo 'Item does not have a price set'; } } Resources: http://php.net/foreach http://php.net/array_key_exists -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ Karl DeSaulniers Design Drumm http://designdrumm.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Would this work for you? http://us.php.net/manual/en/function.xml-parse-into-struct.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe,
Re: [PHP] Arrays
On Feb 26, 2013, at 10:35 PM, tamouse mailing lists wrote: On Mon, Feb 25, 2013 at 9:51 PM, Karl DeSaulniers k...@designdrumm.com wrote: Never mind. I found a different function that reads out the children as well into the array. function xml_parse_into_assoc($data) { $p = xml_parser_create(); xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($p, $data, $vals, $index); xml_parser_free($p); $levels = array(null); foreach ($vals as $val) { if ($val['type'] == 'open' || $val['type'] == 'complete') { if (!array_key_exists($val['level'], $levels)) { $levels[$val['level']] = array(); } } $prevLevel = $levels[$val['level'] - 1]; $parent = $prevLevel[sizeof($prevLevel)-1]; if ($val['type'] == 'open') { $val['children'] = array(); array_push($levels[$val['level']], $val); continue; } else if ($val['type'] == 'complete') { $parent['children'][$val['tag']] = $val['value']; } else if ($val['type'] == 'close') { $pop = array_pop($levels[$val['level']]); $tag = $pop['tag']; if ($parent) { if (!array_key_exists($tag, $parent['children'])) { $parent['children'][$tag] = $pop['children']; } else if (is_array($parent['children'][$tag])) { if(!isset($parent['children'] [$tag][0])) { $oldSingle = $parent['children'][$tag]; $parent['children'][$tag] = null; $parent['children'][$tag][] = $oldSingle; } $parent['children'][$tag][] = $pop['children']; } } else { return(array($pop['tag'] = $pop['children'])); } } $prevLevel[sizeof($prevLevel)-1] = $parent; } } $params = xml_parse_into_assoc($result);// $result = xml result from USPS api Original function by: jemptymethod at gmail dot com Duplicate names fix by: Anonymous (comment right above original function) Best, Karl On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote: On 02/25/2013 05:40 PM, Karl DeSaulniers wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com This will never work. Your last array will always overwrite your previous array. Here is how I would suggest building it: $items = array( 1 = array( serviceid = 1, servicename= signature required, price = $4.95 ), 15 = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) This will ensure that your first level indexes never overwrite themselves. But, with that change made, then do this: foreach ( $items AS $item ) { if ( array_key_exists('price', $item) ) { echo $item['price']; } else { echo 'Item does not have a price set'; } } Resources: http://php.net/foreach http://php.net/array_key_exists -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ Karl DeSaulniers Design Drumm http://designdrumm.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Would this work for you? http://us.php.net/manual/en/function.xml-parse-into-struct.php That is where I got this function. :) Comment 12 and 13 on that page. Yes it worked for me. Best, Karl DeSaulniers Design Drumm
[PHP] Arrays
Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com
Re: [PHP] Arrays
On Mon, Feb 25, 2013 at 8:40 PM, Karl DeSaulniers k...@designdrumm.com wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. Something appears to be amiss, as your array couldn't contain multiple items with the specialservice key (I'm assuming the second key 'secialservice' is just a typo), as any subsequent assignments would overwrite the previous value. Adam -- Nephtali: A simple, flexible, fast, and security-focused PHP framework http://nephtaliproject.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
On 02/25/2013 05:40 PM, Karl DeSaulniers wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com This will never work. Your last array will always overwrite your previous array. Here is how I would suggest building it: $items = array( 1 = array( serviceid = 1, servicename= signature required, price = $4.95 ), 15 = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) This will ensure that your first level indexes never overwrite themselves. But, with that change made, then do this: foreach ( $items AS $item ) { if ( array_key_exists('price', $item) ) { echo $item['price']; } else { echo 'Item does not have a price set'; } } Resources: http://php.net/foreach http://php.net/array_key_exists -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
On Feb 25, 2013, at 7:48 PM, Adam Richardson wrote: On Mon, Feb 25, 2013 at 8:40 PM, Karl DeSaulniers k...@designdrumm.com wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. Something appears to be amiss, as your array couldn't contain multiple items with the specialservice key (I'm assuming the second key 'secialservice' is just a typo), as any subsequent assignments would overwrite the previous value. Adam -- Nephtali: A simple, flexible, fast, and security-focused PHP framework http://nephtaliproject.com Hi Adam, Actually you are correct. Sorry to confuse. Its an XML response from the USPS api I am going through, which I am converting to an array. Here is the response that I am trying to convert to a multidimensional array. ?xml version=1.0? RateV4ResponsePackage ID=1STZipOrigination75287/ ZipOriginationZipDestination87109/ZipDestinationPounds70/ PoundsOunces0/OuncesContainerRECTANGULAR/ ContainerSizeLARGE/SizeWidth2/WidthLength15/ LengthHeight10/HeightZone4/ZonePostage CLASSID=1MailServicePriority Maillt;supgt;amp;reg;lt;/ supgt;/MailServiceRate62.95/ RateSpecialServicesSpecialServiceServiceID1/ ServiceIDServiceNameInsurance/ServiceNameAvailabletrue/ AvailableAvailableOnlinetrue/AvailableOnlinePrice1.95/ PricePriceOnline1.95/PriceOnlineDeclaredValueRequiredtrue/ DeclaredValueRequiredDueSenderRequiredfalse/DueSenderRequired/ SpecialServiceSpecialServiceServiceID0/ ServiceIDServiceNameCertified Maillt;supgt;amp;reg;lt;/supgt;/ ServiceNameAvailabletrue/AvailableAvailableOnlinefalse/ AvailableOnlinePrice3.10/PricePriceOnline0/PriceOnline/ SpecialServiceSpecialServiceServiceID19/ ServiceIDServiceNameAdult Signature Required/ ServiceNameAvailablefalse/AvailableAvailableOnlinetrue/ AvailableOnlinePrice0/PricePriceOnline4.95/PriceOnline/ SpecialService/SpecialServices/Postage/PackagePackage ID=2NDZipOrigination75287/ZipOriginationZipDestination87109/ ZipDestinationPounds55/PoundsOunces0/ OuncesContainerRECTANGULAR/ContainerSizeLARGE/SizeWidth2/ WidthLength15/LengthHeight10/HeightZone4/ZonePostage CLASSID=1MailServicePriority Maillt;supgt;amp;reg;lt;/ supgt;/MailServiceRate52.55/ RateSpecialServicesSpecialServiceServiceID1/ ServiceIDServiceNameInsurance/ServiceNameAvailabletrue/ AvailableAvailableOnlinetrue/AvailableOnlinePrice1.95/ PricePriceOnline1.95/PriceOnlineDeclaredValueRequiredtrue/ DeclaredValueRequiredDueSenderRequiredfalse/DueSenderRequired/ SpecialServiceSpecialServiceServiceID0/ ServiceIDServiceNameCertified Maillt;supgt;amp;reg;lt;/supgt;/ ServiceNameAvailabletrue/AvailableAvailableOnlinefalse/ AvailableOnlinePrice3.10/PricePriceOnline0/PriceOnline/ SpecialServiceSpecialServiceServiceID19/ ServiceIDServiceNameAdult Signature Required/ ServiceNameAvailablefalse/AvailableAvailableOnlinetrue/ AvailableOnlinePrice0/PricePriceOnline4.95/PriceOnline/ SpecialService/SpecialServices/Postage/Package/RateV4Response This is my attempt to convert. I thought of setting up a blank array then filling that array with the specialservice arrays $data = strstr($result, '?'); // echo '!-- '. $data. ' --'; // Uncomment to show XML in comments $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser,XML_OPTION_TARGET_ENCODING, ISO-8859-1); xml_parse_into_struct($xml_parser, $result, $vals, $index); xml_parser_free($xml_parser); $params = array(); $level = array(); foreach ($vals as $xml_elem) { if ($xml_elem['type'] == 'open') { if (array_key_exists('attributes',$xml_elem)) { list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']); } else { $level[$xml_elem['level']] = $xml_elem['tag']; } } if ($xml_elem['type'] == 'complete') { $start_level = 1; $php_stmt = '$params'; while($start_level $xml_elem['level']) { $php_stmt .= '[$level['.$start_level.']]'; $start_level++; } $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];'; eval($php_stmt); } } ... then trying to pull data from the results of the $php_stmt $sid = array(); $numserv = count($params['RATEV4RESPONSE'][''.$p.$ack.''][$cId] ['SPECIALSERVICES']); if($numserv 0) { foreach($params['RATEV4RESPONSE'][''.$p.$ack.''][$cId] ['SPECIALSERVICES']['SPECIALSERVICE'] as $sp_servs) { $sid_val =
Re: [PHP] Arrays
On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote: On 02/25/2013 05:40 PM, Karl DeSaulniers wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com This will never work. Your last array will always overwrite your previous array. Here is how I would suggest building it: $items = array( 1 = array( serviceid = 1, servicename= signature required, price = $4.95 ), 15 = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) This will ensure that your first level indexes never overwrite themselves. But, with that change made, then do this: foreach ( $items AS $item ) { if ( array_key_exists('price', $item) ) { echo $item['price']; } else { echo 'Item does not have a price set'; } } Resources: http://php.net/foreach http://php.net/array_key_exists -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ Thanks Jim, However I have no control over how the USPS sends back the response. See my more detailed email. Best, Karl DeSaulniers Design Drumm http://designdrumm.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
Never mind. I found a different function that reads out the children as well into the array. function xml_parse_into_assoc($data) { $p = xml_parser_create(); xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($p, $data, $vals, $index); xml_parser_free($p); $levels = array(null); foreach ($vals as $val) { if ($val['type'] == 'open' || $val['type'] == 'complete') { if (!array_key_exists($val['level'], $levels)) { $levels[$val['level']] = array(); } } $prevLevel = $levels[$val['level'] - 1]; $parent = $prevLevel[sizeof($prevLevel)-1]; if ($val['type'] == 'open') { $val['children'] = array(); array_push($levels[$val['level']], $val); continue; } else if ($val['type'] == 'complete') { $parent['children'][$val['tag']] = $val['value']; } else if ($val['type'] == 'close') { $pop = array_pop($levels[$val['level']]); $tag = $pop['tag']; if ($parent) { if (!array_key_exists($tag, $parent['children'])) { $parent['children'][$tag] = $pop['children']; } else if (is_array($parent['children'][$tag])) { if(!isset($parent['children'][$tag][0])) { $oldSingle = $parent['children'][$tag]; $parent['children'][$tag] = null; $parent['children'][$tag][] = $oldSingle; } $parent['children'][$tag][] = $pop['children']; } } else { return(array($pop['tag'] = $pop['children'])); } } $prevLevel[sizeof($prevLevel)-1] = $parent; } } $params = xml_parse_into_assoc($result);//$result = xml result from USPS api Original function by: jemptymethod at gmail dot com Duplicate names fix by: Anonymous (comment right above original function) Best, Karl On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote: On 02/25/2013 05:40 PM, Karl DeSaulniers wrote: Hi Guys/Gals, If I have an multidimensional array and it has items that have the same name in it, how do I get the values of each similar item? EG: specialservices = array( specialservice = array( serviceid = 1, servicename= signature required, price = $4.95 ), secialservice = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) How do I get the prices for each? What would be the best way to do this? Can I utilize the serviceid to do this somehow? It is always going to be different per specialservice. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com This will never work. Your last array will always overwrite your previous array. Here is how I would suggest building it: $items = array( 1 = array( serviceid = 1, servicename= signature required, price = $4.95 ), 15 = array( serviceid = 15, servicename = return receipt, price = $2.30 ) ) This will ensure that your first level indexes never overwrite themselves. But, with that change made, then do this: foreach ( $items AS $item ) { if ( array_key_exists('price', $item) ) { echo $item['price']; } else { echo 'Item does not have a price set'; } } Resources: http://php.net/foreach http://php.net/array_key_exists -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ Karl DeSaulniers Design Drumm http://designdrumm.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On 2/7/12 1:50 PM, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. Thanks! Micky Drupal's coding standards encourage the extra trailing comma on multi-line arrays, for all the readability and editability benefits that others have mentioned. We have for years. Cool stuff. :-) --Larry Garfield -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On 12-02-07 02:50 PM, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. JavaScript in Internet Crapsplorer spanks you on the bottom every time you have a trailing comma in a JS array. That may be where you picked up the aversion. 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] Arrays: Comma at end?
On Wed, Feb 8, 2012 at 9:58 AM, Larry Garfield la...@garfieldtech.com wrote: Drupal's coding standards encourage the extra trailing comma on multi-line arrays, for all the readability and editability benefits that others have mentioned. We have for years. Cool stuff. :-) Yah, I love that syntax guideline/rule in Python (tuples and other things). I will definitely start doing this in PHP for arrays. I am just surprised that there wasn't an older version of PHP that did not allow this... I must have picked up this habit via my JS coding knowledge. :D Thanks again all! Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Wed, Feb 8, 2012 at 10:08 AM, Robert Cummings rob...@interjinn.com wrote: JavaScript in Internet Crapsplorer spanks you on the bottom every time you have a trailing comma in a JS array. That may be where you picked up the aversion. On Wed, Feb 8, 2012 at 10:10 AM, Micky Hulse rgmi...@gmail.com wrote: I am just surprised that there wasn't an older version of PHP that did not allow this... I must have picked up this habit via my JS coding knowledge. :D Jinx! You owe me a Coke!!! :) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On 12-02-08 01:12 PM, Micky Hulse wrote: On Wed, Feb 8, 2012 at 10:08 AM, Robert Cummingsrob...@interjinn.com wrote: JavaScript in Internet Crapsplorer spanks you on the bottom every time you have a trailing comma in a JS array. That may be where you picked up the aversion. On Wed, Feb 8, 2012 at 10:10 AM, Micky Hulsergmi...@gmail.com wrote: I am just surprised that there wasn't an older version of PHP that did not allow this... I must have picked up this habit via my JS coding knowledge. :D Jinx! You owe me a Coke!!! :) The timestamps above clearly show I was first ;) 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] Arrays: Comma at end?
Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. Thanks! Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Tue, 2012-02-07 at 11:50 -0800, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. Thanks! Micky It's fine in PHP, and some coding practices actually encourage it, for example: $var = array( 'element', 'element', 'element', ); It's easy to add and remove elements without making sure you have to check the trailing comma. It's also OK in Javascript to use the trailing comma, as long as you don't mind things not working on IE, which is the only browser that has issues with it. As far as PHP goes though, it's fine. -- Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Arrays: Comma at end?
On Tue, Feb 07, 2012 at 11:50:45AM -0800, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. Thanks! Micky I've always avoided trailing array commas, but only because I was under the impression that leaving one there would append a blank array member to the array, where it might be problematic. Yes? No? Paul -- Paul M. Foster http://noferblatz.com http://quillandmouse.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
Hi Ashley! Thanks for your quick and informative reply, I really appreciate it. :) On Tue, Feb 7, 2012 at 12:10 PM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: It's easy to add and remove elements without making sure you have to check the trailing comma. It's also OK in Javascript to use the trailing comma, as long as you don't mind things not working on IE, which is the only browser that has issues with it. As far as PHP goes though, it's fine. Makes sense, thanks! Gosh, I wonder if I picked up this habit due to my JS coding knowledge? Anyway, thanks for the clarification. :) Have an awesome day! Cheers, Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Tue, 2012-02-07 at 15:15 -0500, Paul M Foster wrote: On Tue, Feb 07, 2012 at 11:50:45AM -0800, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? I just did a few quick tests: https://gist.github.com/1761490 ... and it looks like having that comma ain't no big deal. I can't believe that I always thought that having the trailing comma was a no-no in PHP (maybe I picked that up from my C++ classes in college? I just don't remember where I picked up this (bad) habit). I would prefer to have the trailing comma... I just can't believe I have avoided using it for all these years. Thanks! Micky I've always avoided trailing array commas, but only because I was under the impression that leaving one there would append a blank array member to the array, where it might be problematic. Yes? No? Paul -- Paul M. Foster http://noferblatz.com http://quillandmouse.com I've never experienced any blank elements in my arrays, maybe that was a bug that only existed in very specific scenarios? -- Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Arrays: Comma at end?
On Tue, Feb 7, 2012 at 12:15 PM, Paul M Foster pa...@quillandmouse.com wrote: I've always avoided trailing array commas, but only because I was under the impression that leaving one there would append a blank array member to the array, where it might be problematic. Yes? No? Yah, ditto! :D In my few simple tests, using PHP5.x, the last comma is ignored. Just feels strange to have avoided doing something for so long, only to learn that it's something I need not worry about! :D -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Tue, Feb 7, 2012 at 12:19 PM, Micky Hulse rgmi...@gmail.com wrote: Yah, ditto! :D $s = 'foo,bar,'; print_r(explode(',', $s)); The output is: Array ( [0] = foo [1] = bar [2] = ) That's one instance where I know you have to be cautious about the trailing delimiter. I know, this is all noob stuff... Sorry. :D -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On 2/7/12 13:15, Paul M Foster pa...@quillandmouse.com wrote: I've always avoided trailing array commas, but only because I was under the impression that leaving one there would append a blank array member to the array, where it might be problematic. Yes? No? Nope. In fact, it's officially supported syntax: http://us3.php.net/manual/en/function.array.php I love it, particularly when used with the already-noted multi-line array syntax (I don't recommend it with single-line arrangements): $foo = array( 1, 2, 3, ); //$foo This makes it dead easy to add, remove, or reorder elements without worrying about accidentally breaking the syntax. Much like always using braces around flow-control blocks, this practice makes future bugs less likely to be born. Now if only we could have support for trailing commas in SQL UPDATE/INSERT field and value lists Regards, Bob -- Robert E. Williams, Jr. Associate Vice President of Software Development Newtek Businesss Services, Inc. -- The Small Business Authority https://www.newtekreferrals.com/rewjr http://www.thesba.com/ Notice: This communication, including attachments, may contain information that is confidential. It constitutes non-public information intended to be conveyed only to the designated recipient(s). If the reader or recipient of this communication is not the intended recipient, an employee or agent of the intended recipient who is responsible for delivering it to the intended recipient, or if you believe that you have received this communication in error, please notify the sender immediately by return e-mail and promptly delete this e-mail, including attachments without reading or saving them in any manner. The unauthorized use, dissemination, distribution, or reproduction of this e-mail, including attachments, is prohibited and may be unlawful. If you have received this email in error, please notify us immediately by e-mail or telephone and delete the e-mail and the attachments (if any). -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Tue, 2012-02-07 at 12:26 -0800, Micky Hulse wrote: On Tue, Feb 7, 2012 at 12:19 PM, Micky Hulse rgmi...@gmail.com wrote: Yah, ditto! :D $s = 'foo,bar,'; print_r(explode(',', $s)); The output is: Array ( [0] = foo [1] = bar [2] = ) That's one instance where I know you have to be cautious about the trailing delimiter. I know, this is all noob stuff... Sorry. :D That's because it's not an array you've got the trailing delimiter on, it's a string. We were talking about commas on the end of the last element in the array, like: $var = array( 'foo', 'bar', ); That only contains two elements, and won't have a hidden 3rd at any time. -- Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Arrays: Comma at end?
On Tue, Feb 7, 2012 at 12:32 PM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: That's because it's not an array you've got the trailing delimiter on, it's a string. Right. Sorry, bad example. it was just the one example I could think of where you could get an empty element at the end of your array. Clearly, apples and oranges though. Thanks! Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays: Comma at end?
On Wed, Feb 8, 2012 at 4:10 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2012-02-07 at 11:50 -0800, Micky Hulse wrote: Was there ever a time when having a comma at the end of the last array element was not acceptable in PHP? ... It's fine in PHP, and some coding practices actually encourage it, for example: ... It's easy to add and remove elements without making sure you have to check the trailing comma. It's also OK in Javascript to use the trailing comma, as long as you don't mind things not working on IE, which is the only browser that has issues with it. As far as PHP goes though, it's fine. I believe this behavior was inherited from Perl. I used Perl before I used PHP and it was considered a feature for exactly the reason Ash gave. I think that problems with Perl may have originally inspired the creation of PHP, at least in part. But they kept the good parts. This is just my perception. To confirm it, I'd have to ask our BDFL :) -- Vince Aggrippino a.k.a. Ghodmode http://www.ghodmode.com -- Thanks, Ash http://www.ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays passed to functions lose their indexing - how to maintain?
Hi folks, I have an array that looks a little something like this: Array ( [6] = 43.712608, -79.360092 [7] = 43.674088, -79.388557 [8] = 43.674088, -79.388557 [9] = 43.704666, -79.397873 [10] = 43.674393, -79.372147 ) but after I pass it to a function, it loses it's indexing and becomes: Array ( [0] = 43.712608, -79.360092 [1] = 43.674088, -79.388557 [2] = 43.674088, -79.388557 [3] = 43.704666, -79.397873 [4] = 43.674393, -79.372147 ) The indexing is important and I'd like to hang onto it. Any ideas? pointers? Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays passed to functions lose their indexing - how to maintain?
On Fri, 2010-07-09 at 15:55 -0400, Marc Guay wrote: Hi folks, I have an array that looks a little something like this: Array ( [6] = 43.712608, -79.360092 [7] = 43.674088, -79.388557 [8] = 43.674088, -79.388557 [9] = 43.704666, -79.397873 [10] = 43.674393, -79.372147 ) but after I pass it to a function, it loses it's indexing and becomes: Array ( [0] = 43.712608, -79.360092 [1] = 43.674088, -79.388557 [2] = 43.674088, -79.388557 [3] = 43.704666, -79.397873 [4] = 43.674393, -79.372147 ) The indexing is important and I'd like to hang onto it. Any ideas? pointers? Marc Are you passing the array variable by reference? If so, it's probably the logic of the function that is re-writing the keys. What does the function look like? Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Arrays passed to functions lose their indexing - how to maintain?
My bad, I had some leftover code running array_values() on it before it got passed. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays Regexp - Help Requested
Happy New Year, here's my first question of the year (and it's only 15 hours into the year!). I am creating a small database management tool for my a website (my work IP blocks my access to PhpMyAdmin) and I don't want to install any additional software. I am working on adding rows and need to format the input boxes properly (ie. VARCHAR needs an text input, TEXT needs a textarea input). Using a mysql query I can determine the data types for each field. I have a function that uses this information to return datatype specific variables. For example $field['field'] may equal int(6) or varchar(256). The code is a bit extensive, but it's necessary to explain what's going on. ?php // Loop: echo 'table width=100% cellspacing=1 cellpadding=2 border=0' . \n; foreach ($fields as $field) { // ROW BEGIN echo \t . 'tr' . \n; // NAME OF FIELD echo \t\t . 'td`' . $field['field'] . '`: /td' . \n; // FIELD DATA TYPE echo \t\t . 'td' . $field['type'] . '/td' . \n; // VALUE INPUT echo \t\t . 'td'; $input_type = printByType($field['type'], 'INPUT_TYPE'); echo 'input type=' . $input_type . ' '; if ($input_type == 'text') { echo 'size='; $length = printByType($field['type'], 'INPUT_LENGTH'); echo $length; echo ' '; echo 'value='; if ($field['null'] == 'YES') // CAN BE NULL? { echo 'NULL'; } echo ' '; } elseif ($input_type == 'textarea') { echo 'rows=7 cols=30 '; echo 'value='; if ($field['null'] == 'YES') // CAN BE NULL? { echo 'NULL'; } echo ' '; } echo 'name=value[] id=value[] onfocus=if(this.value==\'NULL\')this.value=\'\'; /'; echo '/td' . \n; echo \t . '/tr' . \n; } echo '/table'; ? The function: ?php function printByType($string, $mode) { (string) $string; $lengths = array( 'VARCHAR' = 10 , 'TINYINT' = 1 , 'TEXT' = 10 , 'DATE' = 7 , 'SMALLINT' = 1 , 'MEDIUMINT' = 2 , 'INT' = 2 , 'BIGINT' = 3 , 'FLOAT' = 4 , 'DOUBLE' = 4 , 'DECIMAL' = 4 , 'DATETIME' = 10 , 'TIMESTAMP' = 10 , 'TIME' = 7 , 'YEAR' = 4 , 'CHAR' = 7 , 'TINYBLOB' = 10 , 'TINYTEXT' = 10 , 'BLOB' = 10 , 'MEDIUMBLOB' = 10 , 'MEDIUMTEXT' = 10 , 'LONGBLOB' = 10 , 'LONGTEXT' = 10 , 'ENUM' = 5 , 'SET' = 5 , 'BIT' = 2 , 'BOOL' = 1 , 'BINARY' = 10 , 'VARBINARY' = 10); $types = array( 'VARCHAR' = 'text' , 'TINYINT' = 'text' , 'TEXT' = 'textarea' , 'DATE' = 'text' , 'SMALLINT' = 'text' , 'MEDIUMINT' = 'text' , 'INT' = 'text' , 'BIGINT' = 'text' , 'FLOAT' = 'text' , 'DOUBLE' = 'text' , 'DECIMAL' = 'text' , 'DATETIME' = 'text' , 'TIMESTAMP' = 'text' , 'TIME' = 'text' , 'YEAR' = 'text' , 'CHAR' = 'text' , 'TINYBLOB' = 'textarea' , 'TINYTEXT' = 'textarea' , 'BLOB' = 'textarea' , 'MEDIUMBLOB' = 'textarea' , 'MEDIUMTEXT' = 'textarea' , 'LONGBLOB' = 'textarea' , 'LONGTEXT' = 'textarea' , 'ENUM' = 'text' , 'SET' = 'text' , 'BIT' = 'text' , 'BOOL' = 'text' , 'BINARY' = 'text' , 'VARBINARY' = 'text'); switch ($mode) { case 'INPUT_LENGTH': foreach ($lengths as $key = $val) { (string) $key; (int) $val; // DETERMINE LENGTH VALUE eg. int(6) GETS 6 preg_match('#\((.*?)\)#', $string, $match); (int) $length_value = $match[1]; // SEARCH $regex = / . strtolower($key) . /i; $found = preg_match($regex, $string); if ($found !== false) { // DETERMINE ADD INTEGER eg. If the length_value is long enough, determine number to increase html input length switch ($length_value) { case ($length_value = 7): return $length_value; break; case ($length_value 7 $length_value 15): return $val += ($length_value/2); break; case ($length_value 14 $length_value 101): $result = ($length_value / 5); $divide = ceil($result); return $val += $divide; break; case ($length_value 100): return 40; break; default: return 7; break; } return $val; } else { return 7; // default value } } break; case 'INPUT_TYPE': foreach ($types as $key = $val) { (string) $val; (string) $key; // SEARCH $regex = / . strtolower($key) . /i; $found = preg_match($regex, $string); if ($found === false) { return 'text'; // default value } else { return $val; } } break; } } ? The first part of the function (the first switch case) works, and the text fields are variable in length, but even the fields with a TEXT datatype is printing out a text box instead of a textarea. Can anyone see why this is happening? Thanks!
Re: [PHP] Arrays Regexp - Help Requested
I think the problem is here: echo 'input type=' . $input_type . ' '; [...snip...] elseif ($input_type == 'textarea') { echo 'rows=7 cols=30 '; echo 'value='; if ($field['null'] == 'YES') // CAN BE NULL? { echo 'NULL'; } echo ' '; } because to create a textarea, the HTML is textarea rows=7 cols=30default text/textarea. It looks like your code is trying to make a textarea that starts with input type=' which won't work. See http://www.w3.org/TR/html401/interact/forms.html#h-17.7 for how to use textarea. On Jan 1, 2010, at 3:38 PM, Allen McCabe wrote: echo 'input type=' . $input_type . ' '; if ($input_type == 'text') { echo 'size='; $length = printByType($field['type'], 'INPUT_LENGTH'); echo $length; echo ' '; echo 'value='; if ($field['null'] == 'YES') // CAN BE NULL? { echo 'NULL'; } echo ' '; } elseif ($input_type == 'textarea') { echo 'rows=7 cols=30 '; echo 'value='; if ($field['null'] == 'YES') // CAN BE NULL? { echo 'NULL'; } echo ' '; } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Hidden costs of PHP arrays?
On Jan 29, 2009, at 6:07 PM, Eric Butera eric.but...@gmail.com wrote: On Thu, Jan 29, 2009 at 9:02 PM, Paul M Foster pa...@quillandmouse.com wrote: On Fri, Jan 30, 2009 at 11:10:16AM +1100, Clancy wrote: snip As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. Ahhh, finally someone who understands this principle. There's simply no reason to waste cycles if you don't have to. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Flip side of the coin: also no point in wasting 10 hours accomplishing something that can be done in 2 on a management screen that rarely gets used. :) I know this well. I also work in a framework where 8 nested foreaches can be found. Arrays are hardly expensive in my position... -- http://www.voom.me | EFnet: #voom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php No seriously... http://voom.me | EFnet #voom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Re: Hidden costs of PHP arrays?
-Original Message- From: Paul M Foster [mailto:pa...@quillandmouse.com] Sent: Thursday, January 29, 2009 8:02 PM To: php-general@lists.php.net Subject: Re: [PHP] Re: Hidden costs of PHP arrays? On Fri, Jan 30, 2009 at 11:10:16AM +1100, Clancy wrote: snip As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. Ahhh, finally someone who understands this principle. There's simply no reason to waste cycles if you don't have to. If that's REALLY your bag, just plot all of your functions in Assembly, first! https://www.scriptlance.com/cgi-bin/freelancers/project.cgi?id=121743701 3order=bid%20DESC I, for one, will keep efficiency in mind--but if I spend a couple extra cycles to relieve myself of an extra 20 lines of code, I think I'll sleep just fine. :) Now, if I was programming embedded systems or time-critical transaction processing software, that might be another story. (Then again, if that were the case, I might not be playing with an interpreted language to begin with.) My 2c. // Todd -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Hidden costs of PHP arrays?
On Wed, 28 Jan 2009 00:50:18 +, nrix...@gmail.com (Nathan Rixham) wrote: Clancy wrote: Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; Thanks to everyone who has commented. if you go for option b; you're going to have do a vast amount of isset() checks in a for loop and all kinds of fancy business logic for $contacts['clancy']['home_phone'] = 0123 4567; vs $contacts['clancy']['home_phone'] = ''; vs 'home_phone' not set This question is far less clear-cut than you might assume. The data is actually stored as a text document, with a separate line for each piece of information. To minimise the file length blank fields are simply omitted. When I load the file into memory it is much simpler to enter only the fields which are actually specified. As there are ~600 entries this presumably gives a significant saving in loading time and in memory. However if I take this approach I then have to add an if(isset( ...)) test before I read each field when I'm trying to access a specific entry. This would only increase the memory usage by a very small amount, and would have a negligible effect on timing. So if I fill in all the entries when I load the file it will increase the loading times slightly, and use slightly more memory. On the other hand it will save me from having to think about it whenever I access a variable. The question really comes down to whether the saving in memory if I don't load the empty variables is worth the extra programming hassle when I write new procedures for accessing an entry. so one would guess that code would far outweigh any tiny speed gain from dropping the additional items in the array. on another note; php has been stable and speedy now for a very long time, some bit's like the reflection api could be speeded up a little bit as demand grows, but certainly all scalars and compound types have been tested and optimized to hell and back (afaik). One could reasonably hope that the same could be said for every part of the programming chain, but it is one of the ironies of modern computing that computers get faster and faster, memory gets cheaper and cheaper, programming appears to get simpler and simpler, yet the programs get slower and slower. I have a fairly modern (maybe 2yo) computer, and use XP professional 5.1. Not long ago I switched to Office 2007 12.0, and when I did so I was appalled to discover that if I had a document loaded into Word, and hit Ctrl A, I could watch the highlighting scroll down the screen! As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. you can test this all you're self, simply populate an array with say 1000 random other arrays of data with 10 keys each, stick it in a for loop and time several times, then do the same for an array as above but with subarrays of only 5 keys; see if you can spot any significant difference. [then compare to say a single database select, or an execution of a small script.] another way of putting it; I'm 99% sure that nobodies code is perfectly optimised enough by itself to notice any performance hits from php; quite sure you could make far bigger gains by optimising you're own code first :p regards! ramble -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] MicroSlow Software (was: Re: Hidden costs of PHP arrays?)
Clancy wrote: One could reasonably hope that the same could be said for every part of the programming chain, but it is one of the ironies of modern computing that computers get faster and faster, memory gets cheaper and cheaper, programming appears to get simpler and simpler, yet the programs get slower and slower. I have a fairly modern (maybe 2yo) computer, and use XP professional 5.1. Not long ago I switched to Office 2007 12.0, and when I did so I was appalled to discover that if I had a document loaded into Word, and hit Ctrl A, I could watch the highlighting scroll down the screen! As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. I would venture to say that it's Microsoft Software that is slower with every release. PHP, Apache, MySQL, and Linux always improve their newer builds for speed whenever possible. 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] Re: Hidden costs of PHP arrays?
On Fri, Jan 30, 2009 at 11:10:16AM +1100, Clancy wrote: snip As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. Ahhh, finally someone who understands this principle. There's simply no reason to waste cycles if you don't have to. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Hidden costs of PHP arrays?
On Thu, Jan 29, 2009 at 9:02 PM, Paul M Foster pa...@quillandmouse.com wrote: On Fri, Jan 30, 2009 at 11:10:16AM +1100, Clancy wrote: snip As a former assembly language programmer I have some idea of the vast amount of thumb twiddling which is going on behind-the-scenes when I make some apparently simple request like the one to get my phone number. Undoubtedly most of this occurs in the murky depths of the operating system, but if there were any simple way to avoid adding to it unnecessarily it would be nice to know about it. Ahhh, finally someone who understands this principle. There's simply no reason to waste cycles if you don't have to. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Flip side of the coin: also no point in wasting 10 hours accomplishing something that can be done in 2 on a management screen that rarely gets used. :) -- http://www.voom.me | EFnet: #voom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Hidden costs of PHP arrays?
PHP arrays permit extremely concise programming; for example if I have all my contacts in an array $contacts, I can write: $my_phone_no = $contacts['clancy']['phone']; However it is clear that there must be a lot going on behind the scenes to achieve this simple result, as it requires some sort of search procedure. Is it possible to give any indication of the overheads and memory costs that are involved in such a statement, and of how well the search procedure is implemented? Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; And is there any advantage in always assigning the keys in the same order? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Hidden costs of PHP arrays?
2009/1/28 Clancy clanc...@cybec.com.au PHP arrays permit extremely concise programming; for example if I have all my contacts in an array $contacts, I can write: $my_phone_no = $contacts['clancy']['phone']; However it is clear that there must be a lot going on behind the scenes to achieve this simple result, as it requires some sort of search procedure. Is it possible to give any indication of the overheads and memory costs that are involved in such a statement, and of how well the search procedure is implemented? Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; And is there any advantage in always assigning the keys in the same order? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Well, arrays of those types are, as far as I know, stored as hash tables. So you should look for how hash tables work. -eddy
[PHP] Re: Hidden costs of PHP arrays?
Clancy wrote: Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; if you go for option b; you're going to have do a vast amount of isset() checks in a for loop and all kinds of fancy business logic for $contacts['clancy']['home_phone'] = 0123 4567; vs $contacts['clancy']['home_phone'] = ''; vs 'home_phone' not set so one would guess that code would far outweigh any tiny speed gain from dropping the additional items in the array. on another note; php has been stable and speedy now for a very long time, some bit's like the reflection api could be speeded up a little bit as demand grows, but certainly all scalars and compound types have been tested and optimized to hell and back (afaik). you can test this all you're self, simply populate an array with say 1000 random other arrays of data with 10 keys each, stick it in a for loop and time several times, then do the same for an array as above but with subarrays of only 5 keys; see if you can spot any significant difference. [then compare to say a single database select, or an execution of a small script.] another way of putting it; I'm 99% sure that nobodies code is perfectly optimised enough by itself to notice any performance hits from php; quite sure you could make far bigger gains by optimising you're own code first :p regards! ramble -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Hidden costs of PHP arrays?
On Wed, 2009-01-28 at 10:38 +1100, Clancy wrote: PHP arrays permit extremely concise programming; for example if I have all my contacts in an array $contacts, I can write: $my_phone_no = $contacts['clancy']['phone']; However it is clear that there must be a lot going on behind the scenes to achieve this simple result, as it requires some sort of search procedure. Is it possible to give any indication of the overheads and memory costs that are involved in such a statement, and of how well the search procedure is implemented? Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; And is there any advantage in always assigning the keys in the same order? Lookup is O( lg n ). Since your examples above are nested 2 levels deep then it's actually 2 * O( lg n ) which is O( lg n ). But really, the variable itself, $contacts is probably also looked up and it is also O( lg n ) and of course 3 * O( lg n ) is still O( lg n ). Moving along... for arbitrary depth paths, you'd be talking O( m lg n ) but for realistic cases you'll not get deep enough for that to matter much. Either way, if you are looping over an array and always accessing X levels deep, you might want to create a temporary variable that is level X - 1 (unless that's not a possible option). 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] Hidden costs of PHP arrays?
Robert Cummings wrote: On Wed, 2009-01-28 at 10:38 +1100, Clancy wrote: PHP arrays permit extremely concise programming; for example if I have all my contacts in an array $contacts, I can write: $my_phone_no = $contacts['clancy']['phone']; However it is clear that there must be a lot going on behind the scenes to achieve this simple result, as it requires some sort of search procedure. Is it possible to give any indication of the overheads and memory costs that are involved in such a statement, and of how well the search procedure is implemented? Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; And is there any advantage in always assigning the keys in the same order? Lookup is O( lg n ). Since your examples above are nested 2 levels deep then it's actually 2 * O( lg n ) which is O( lg n ). But really, the variable itself, $contacts is probably also looked up and it is also O( lg n ) and of course 3 * O( lg n ) is still O( lg n ). Moving along... for arbitrary depth paths, you'd be talking O( m lg n ) but for realistic cases you'll not get deep enough for that to matter much. Either way, if you are looping over an array and always accessing X levels deep, you might want to create a temporary variable that is level X - 1 (unless that's not a possible option). Cheers, Rob. rob; go apply for a job at yahoo - that's one of there interview questions for new developers [describe o notation] is impressed - v nice answer -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays?
Nicholas Yim wrote: Hello William Stokes, 1 write a callback function: [php] function cmp_forth_value($left,$right){ return $left[4]$right?-1:($left[4]==$right[4]?0:1); return $left[4]$right[4]?-1:($left[4]==$right[4]?0:1); ^^^ add this } [/php] 2 use the usort function usort($test,'cmp_forth_value'); Best regards, -- Thanking You Sumeet Shroff http://www.prateeksha.com Web Designers and PHP / Mysql Ecommerce Development, Mumbai India -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays?
Nicholas Yim wrote: Hello William Stokes, 1 write a callback function: [php] function cmp_forth_value($left,$right){ return $left[4]$right?-1:($left[4]==$right[4]?0:1); return $left[4]$right[4]?-1:($left[4]==$right[4]?0:1); ^^^ add this } [/php] 2 use the usort function usort($test,'cmp_forth_value'); Best regards, -- Thanking You Sumeet Shroff http://www.prateeksha.com Web Designers and PHP / Mysql Ecommerce Development, Mumbai India -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays?
Hello, How to print out the following array $test so that the print order is by the fourth[4] key? I need to print out all arrays in $test so that the data is ordered by the fourth key in ascending order. $test =Array ( [0] = Array ( [0] = 5 [1] = 2 [2] = sika [3] = sika.php [4] = 1 ) [1] = Array ( [0] = 8 [1] =2 [2] = Hono [3] = hono.php [4] = 1 ) [2] = Array ( [0] = 7 [1] = 2 [2] = Kameli [3] = kameli.php [4] = 4 ) [3] = Array ( [0] = 6 [1] = 2 [2] = koira [3] = koira.php [4] = 2 ) ) The way that the data is strored to $test makes it difficult/impossible to sort stuff the way I need here while reading it from DB. Thanks -Will -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays?
Hello William Stokes, 1 write a callback function: [php] function cmp_forth_value($left,$right){ return $left[4]$right?-1:($left[4]==$right[4]?0:1); } [/php] 2 use the usort function usort($test,'cmp_forth_value'); Best regards, === At 2007-01-08, 14:46:33 you wrote: === Hello, How to print out the following array $test so that the print order is by the fourth[4] key? I need to print out all arrays in $test so that the data is ordered by the fourth key in ascending order. $test =Array ( [0] = Array ( [0] = 5 [1] = 2 [2] = sika [3] = sika.php [4] = 1 ) [1] = Array ( [0] = 8 [1] =2 [2] = Hono [3] = hono.php [4] = 1 ) [2] = Array ( [0] = 7 [1] = 2 [2] = Kameli [3] = kameli.php [4] = 4 ) [3] = Array ( [0] = 6 [1] = 2 [2] = koira [3] = koira.php [4] = 2 ) ) The way that the data is strored to $test makes it difficult/impossible to sort stuff the way I need here while reading it from DB. Thanks -Will -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php = = = = = = = = = = = = = = = = = = = = Nicholas Yim [EMAIL PROTECTED] 2007-01-08 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays help
Hello, I'm making a menu script that uses mysql, php and javascript to build a on mouse over dropdown menu to a page. I ran into some problems and would need help to get this working. (This is just the top level of the menusystem) 1. Get the toplevel links from DB, create array and put values there. $sql =SELECT * FROM x_menu WHERE menulevel = '1' ORDER BY 'id' ASC; $result=mysql_query($sql); $num = mysql_num_rows($result); $cur = 1; while ($num = $cur) { $row = mysql_fetch_array($result); $id = $row[id]; $menulevel = $row[menulevel]; $linktext = $row[linktext]; $linkurl = $row[linkurl]; $toplevel =array($id, $menulevel, $linktext, $linkurl); $cur ++; } The first problem comes here. How can I create a different array at every iteration of the loop? Or how this should be done if the toplevel objects are echoed with foreach to the browser like this: $TopLevelCounter = 1; foreach ($toplevel as $value){ print menuSyS.addItem('labelItem', '$toplevel[2]', $TopLevelCounter, $width, '$colour1', '#aa', '$colour2');\n; $TopLevelCounter ++; } Now, because I just fill the same array again and again in the DB query all top level items finally contain the same text. So my question is how to query the DB and create the arrays so that it would be easy to refer to the data in the arrays when printing to screen. Do I have to make multidimensional arrays? If so how to implement them here and how they should be referred to when printing to browser? Thanks -Will -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays help
On Fri, 2007-01-05 at 18:48 +0200, William Stokes wrote: Hello, I'm making a menu script that uses mysql, php and javascript to build a on mouse over dropdown menu to a page. I ran into some problems and would need help to get this working. (This is just the top level of the menusystem) 1. Get the toplevel links from DB, create array and put values there. $sql =SELECT * FROM x_menu WHERE menulevel = '1' ORDER BY 'id' ASC; Yeesh... should be using parent ID references. How does a sub-menu item know to which menu item it belongs? It has a parent right? What determines a root menu entry? No parent (or root node parent)... What is this wierd menulevel field? $result=mysql_query($sql); $num = mysql_num_rows($result); $cur = 1; while ($num = $cur) { $row = mysql_fetch_array($result); $id = $row[id]; $menulevel = $row[menulevel]; $linktext = $row[linktext]; $linkurl = $row[linkurl]; $toplevel =array($id, $menulevel, $linktext, $linkurl); $cur ++; } The first problem comes here. How can I create a different array at every iteration of the loop? Or how this should be done if the toplevel objects are echoed with foreach to the browser like this: Just create the array at each iteration of the loop... $foo = array( /* put some data in it */ ) $TopLevelCounter = 1; foreach ($toplevel as $value){ print menuSyS.addItem('labelItem', '$toplevel[2]', $TopLevelCounter, $width, '$colour1', '#aa', '$colour2');\n; $TopLevelCounter ++; } Now, because I just fill the same array again and again in the DB query all top level items finally contain the same text. So my question is how to query the DB and create the arrays so that it would be easy to refer to the data in the arrays when printing to screen. Do I have to make multidimensional arrays? Yes. If so how to implement them here and how they should be referred to when printing to browser? Use a foreach loop for the menu array. When you come across a menu item with children, use another foreach loop. Alternatively you can use recursion. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Parsing serialized PHP arrays in C
On Sat, October 21, 2006 6:25 pm, Kevin Wilcox wrote: ext/standard/var_unserializer.c, and I don't think what will port to a That's pretty much the code I would have pointed you to... Unless you happen to KNOW that all the data inside the arrays is ultimately scaler or something... I suppose you've already ruled out just installing PHP and using exec() in C to call it? -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Parsing serialized PHP arrays in C
I have a feeling this may be the wrong group to ask this question, but I thought that if it is, someone can point me in the right direction. I'm working on a application written in C that needs to parse and understand php arrays that have been serialized and stored in a MySQL table. I started writing the parser and realized its not a trivial task. I'm wondering if there is any source code in C to do what I'm looking for? I googled many different combinations of keywords and nothing useful came up. I even looked at the code in ext/standard/var_unserializer.c, and I don't think what will port to a stand alone application without extensive modifications. Any help would be greatly appreciated. Thanks, Kevin -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Parsing serialized PHP arrays in C
Kevin Wilcox wrote: I have a feeling this may be the wrong group to ask this question, but I thought that if it is, someone can point me in the right direction. I'm working on a application written in C that needs to parse and understand php arrays that have been serialized and stored in a MySQL table. I started writing the parser and realized its not a trivial task. I'm wondering if there is any source code in C to do what I'm looking for? I googled many different combinations of keywords and nothing useful came up. I even looked at the code in ext/standard/var_unserializer.c, and I don't think what will port to a stand alone application without extensive modifications. Why not? It is a rather simple re2c parser. Don't look at var_unserializer.c, look at var_unserializer.re and read up on re2c. http://re2c.org/ You would obviously want to replace the creation of internal PHP data types with whatever you want to unserialize to in your app, but I don't see how you would find any code somewhere else where you wouldn't need to yank out the destination code from since that is going to be the unique part in each implementation. And if you use the same re2c grammar that PHP uses, it will be correct. Using any other implementation likely wouldn't be. Of course, I also wouldn't suggest using serialized PHP for a target that wasn't PHP. Why don't you look at json or perhaps wddx instead? -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays
At 3:38 PM -0400 7/10/06, Dallas Cahker wrote: Banging my head against a wall with arrays, maybe someone can help me with the answer. I have a db query that returns results from 1-100 or more. I want to put the results into an array and pull them out elsewhere. I want them to be pulled out in an orderly and expected fashion. Dallas: Place the sorting on MySQL -- it has great ways of providing data for you. Perhaps this link might help: http://www.weberdev.com/get_example-4270.html 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
[PHP] arrays
Banging my head against a wall with arrays, maybe someone can help me with the answer. I have a db query that returns results from 1-100 or more. I want to put the results into an array and pull them out elsewhere. I want them to be pulled out in an orderly and expected fashion. part of function $sql=Select * FROM blah Where blahid='1'; run sql while ($row=mysql_fetch_array($result)) { $oarray=array('blah1' = $row['lah1'], 'blah2' = $row['lah2'], 'blah3' = $row['lah3']); } return $oarray part of display $OLength=count($oarray); for ($i = 0; $i $OLength; $i++){ echo O1 : .$oarray['blah1'][$i].br; echo O2 : .$oarray['blah2'][$i].br; echo O3 : .$oarray['blah3'][$i].br; } this gets me nothing, and I am unsure where I am going wrong, other then all over the place.
Re: [PHP] arrays
Dallas Cahker wrote: Banging my head against a wall with arrays, maybe someone can help me with the answer. I have a db query that returns results from 1-100 or more. I want to put the results into an array and pull them out elsewhere. I want them to be pulled out in an orderly and expected fashion. part of function $sql=Select * FROM blah Where blahid='1'; run sql while ($row=mysql_fetch_array($result)) { $oarray=array('blah1' = $row['lah1'], 'blah2' = $row['lah2'], 'blah3' = $row['lah3']); The above line will not add an array element per row. Change $oarray= to $oarray[]= } return $oarray part of display $OLength=count($oarray); for ($i = 0; $i $OLength; $i++){ echo O1 : .$oarray['blah1'][$i].br; echo O2 : .$oarray['blah2'][$i].br; echo O3 : .$oarray['blah3'][$i].br; } This is not the way the array is arranged. Switch your indices around so it's like so... echo O1 : .$oarray[$i]['blah1'].br; echo O2 : .$oarray[$i]['blah2'].br; echo O3 : .$oarray[$i]['blah3'].br; this gets me nothing, and I am unsure where I am going wrong, other then all over the place. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays
When loading the array you will only ever get the last record returned... so count($oarray) will always be 1? Perhaps something like this: Function $sql = ...; $ret = array(); while($row = mysql_feth_array($reault)) { array_push($ret, $row); } return $ret; then... $data = function(); $c = count($data); for($i=0; $i$c; $i++) { $row = $data[$i]; print_r($row); } Should give you what you want... As for your orderly fashion, I would put this load on the database, and not really PHP... if you want to make it associate you can...just push the assocative onto another array so you get the complete set... -B Dallas Cahker wrote: Banging my head against a wall with arrays, maybe someone can help me with the answer. I have a db query that returns results from 1-100 or more. I want to put the results into an array and pull them out elsewhere. I want them to be pulled out in an orderly and expected fashion. part of function $sql=Select * FROM blah Where blahid='1'; run sql while ($row=mysql_fetch_array($result)) { $oarray=array('blah1' = $row['lah1'], 'blah2' = $row['lah2'], 'blah3' = $row['lah3']); } return $oarray part of display $OLength=count($oarray); for ($i = 0; $i $OLength; $i++){ echo O1 : .$oarray['blah1'][$i].br; echo O2 : .$oarray['blah2'][$i].br; echo O3 : .$oarray['blah3'][$i].br; } this gets me nothing, and I am unsure where I am going wrong, other then all over the place. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays
Both work great. Thanks On 7/10/06, Brad Bonkoski [EMAIL PROTECTED] wrote: When loading the array you will only ever get the last record returned... so count($oarray) will always be 1? Perhaps something like this: Function $sql = ...; $ret = array(); while($row = mysql_feth_array($reault)) { array_push($ret, $row); } return $ret; then... $data = function(); $c = count($data); for($i=0; $i$c; $i++) { $row = $data[$i]; print_r($row); } Should give you what you want... As for your orderly fashion, I would put this load on the database, and not really PHP... if you want to make it associate you can...just push the assocative onto another array so you get the complete set... -B Dallas Cahker wrote: Banging my head against a wall with arrays, maybe someone can help me with the answer. I have a db query that returns results from 1-100 or more. I want to put the results into an array and pull them out elsewhere. I want them to be pulled out in an orderly and expected fashion. part of function $sql=Select * FROM blah Where blahid='1'; run sql while ($row=mysql_fetch_array($result)) { $oarray=array('blah1' = $row['lah1'], 'blah2' = $row['lah2'], 'blah3' = $row['lah3']); } return $oarray part of display $OLength=count($oarray); for ($i = 0; $i $OLength; $i++){ echo O1 : .$oarray['blah1'][$i].br; echo O2 : .$oarray['blah2'][$i].br; echo O3 : .$oarray['blah3'][$i].br; } this gets me nothing, and I am unsure where I am going wrong, other then all over the place.
[PHP] arrays
if I have two arrays, example: $a = array (one, two, three, four, two); $b = array (seven, one, three, six, five); How can I get in another variable a new array with the same elements into $a and $b. -- Este mensaje ha sido analizado por MailScanner en busca de virus y otros contenidos peligrosos, y se considera que está limpio.
RE: [PHP] arrays
[snip] if I have two arrays, example: $a = array (one, two, three, four, two); $b = array (seven, one, three, six, five); How can I get in another variable a new array with the same elements into $a and $b. [/snip] http://www.php.net/array_merge -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays
Hola Jesus. Hablo un pocitio espanol, pero en ingles no estoy seguro que quieres decir. Si te ayudara, envia el mensaje otra vez en espanol y tratare comprender. On 09/06/06, Jesús Alain Rodríguez Santos [EMAIL PROTECTED] wrote: if I have two arrays, example: $a = array (one, two, three, four, two); $b = array (seven, one, three, six, five); How can I get in another variable a new array with the same elements into $a and $b. -- Este mensaje ha sido analizado por MailScanner en busca de virus y otros contenidos peligrosos, y se considera que está limpio. -- http://www.web-buddha.co.uk dynamic web programming from Reigate, Surrey UK (php, mysql, xhtml, css) look out for project karma, our new venture, coming soon!
Re: [PHP] arrays
On 6/9/06, Jesús Alain Rodríguez Santos [EMAIL PROTECTED] wrote: if I have two arrays, example: $a = array (one, two, three, four, two); $b = array (seven, one, three, six, five); How can I get in another variable a new array with the same elements into $a and $b. php.net/array_intersect will get you the common elements. Rabin -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays
Jess Alain Rodrguez Santos wrote: if I have two arrays, example: $a = array ("one", "two", "three", "four", "two"); $b = array ("seven", "one", "three", "six", "five"); How can I get in another variable a new array with the same elements into $a and $b. $new_array = array_merge( $a, $b); regards, Mariano Guadagnini. No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.394 / Virus Database: 268.8.3/359 - Release Date: 08/06/2006 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Question for PHP Arrays
Hi, I'm making a PHP Installer that is customizable by using plugins, I haven't used PHP for a while and which I have forgotten some things about PHP *eek*.. Anyway, I want to know how to add things to an array. Like this: $foobar = array() $foobar['rar']['miaw'] Would that output come out (for the array) as: array( 'rar' = 'miaw' ) Please correct me if wrong. Also I need to ask one more question, would this work: $foobar = array() function addToArray($int, $value) { $foobar[$int][$value] } And with a function call addToArray(1, meow) output as the array looking like: array( '1' = 'meow' ) -- Thanks, dphiance (Saul Rennison)
Re: [PHP] Question for PHP Arrays
On 27 Apr 2006, at 20:51, Saul Rennison wrote: Anyway, I want to know how to add things to an array. Like this: $foobar = array() $foobar['rar']['miaw'] Would that output come out (for the array) as: array( 'rar' = 'miaw' ) No, it would create a multi-dimensional array that contains nothing. You want: $foobar['rar'] = 'miaw'; Please correct me if wrong. Also I need to ask one more question, would this work: $foobar = array() function addToArray($int, $value) { $foobar[$int][$value] } And with a function call addToArray(1, meow) output as the array looking like: array( '1' = 'meow' ) No (because of the mistake commented on above). However another issue at play here is scope. $foobar the array will not be visible to the function addToArray unless you make it global. Cheers, Rich -- http://www.corephp.co.uk Zend Certified Engineer PHP Development Services -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Question for PHP Arrays
Saul Rennison wrote: Hi, I'm making a PHP Installer that is customizable by using plugins, I haven't used PHP for a while and which I have forgotten some things about PHP *eek*.. $hiddenKnowledge = unforgetPHP(); Anyway, I want to know how to add things to an array. Like this: $foobar = array() $foobar['rar']['miaw'] Would that output come out (for the array) as: array( 'rar' = 'miaw' ) Please correct me if wrong. Also I need to ask one more question, would this work: $foobar = array() function addToArray($int, $value) { $foobar[$int][$value] } And with a function call addToArray(1, meow) output as the array looking like: I think you have been eating too much Ruby (or something like that) because that function won't return or output anything. you need to always specify a value to return. just out of interest; what is stopping you from cut/pasting those 3-4 lines into a file and running it? (it would take less time than it did for you to write your post and the answer you get back from the php binary/module would have been alot less sarcastic than mine) array( '1' = 'meow' ) -- Thanks, dphiance (Saul Rennison) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays
Sorry if this question seems stupid - I've only had 3 days of PHP experience. When using the following string format, I get an error from PHP. $text['text'] = String Text ; Can someone help me? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
At 11:12 AM 2/4/2006, Philip W. wrote: When using the following string format, I get an error from PHP. $text['text'] = String Text ; Hi Philip, If that's literally a line from your script, my guess is that text is a reserved word and can't be used as a variable name. Try $sText or $sSomethingMeaningful. In this and future postings, it would help us help you if you share all relevant details such as the exact error message you see. I've gotten into the habit of prefixing all my variable names with their type: $aSomething - array $sSomething - string $iSomething - integer $nSomething - numeric $bSomething - Boolean In a language like PHP in which data typing is so loose, I find that prefixing the variable type a) helps me keep variables straight and b) prevents me from inadvertantly using reserved words as variable names. Great resource: http://php.net/ You can quickly look up details from the reference guide by entering key words after the domain name, for example: http://php.net/array gets you a page of array functions. Have fun, Paul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
Philip, You'll often get an error call on a line when there is a problem on the previous line. Say, you forgot to end a line with a semicolon, then it will error the next line. Hugh - Original Message - From: Philip W. [EMAIL PROTECTED] To: php-general@lists.php.net Sent: Saturday, February 04, 2006 11:12 AM Subject: [PHP] Arrays Sorry if this question seems stupid - I've only had 3 days of PHP experience. When using the following string format, I get an error from PHP. $text['text'] = String Text ; Can someone help me? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.1.375 / Virus Database: 267.15.1/250 - Release Date: 2/3/2006 -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.375 / Virus Database: 267.15.1/250 - Release Date: 2/3/2006 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays
If I have an array, such as $Var[0] = Dog; $Var[1] = Cat; $Var[2] = Horse; Is there a way to quickly check to see if $Var contains Lion without walking through each value? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Arrays
[snip] Is there a way to quickly check to see if $Var contains Lion without walking through each value? [/snip] http://us3.php.net/in_array -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
On 6 Dec 2005, at 17:33, Ben Miller wrote: If I have an array, such as $Var[0] = Dog; $Var[1] = Cat; $Var[2] = Horse; Is there a way to quickly check to see if $Var contains Lion without walking through each value? Look in the manual at the function in_array() Cheers, Rich -- http://www.corephp.co.uk PHP Development Services -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
This what you want? http://us3.php.net/manual/en/function.array-search.php -TG = = = Original message = = = If I have an array, such as $Var[0] = Dog; $Var[1] = Cat; $Var[2] = Horse; Is there a way to quickly check to see if $Var contains Lion without walking through each value? ___ Sent by ePrompter, the premier email notification software. Free download at http://www.ePrompter.com. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays question
On Fri, 2005-11-11 at 15:25, cybermalandro cybermalandro wrote: I have this that looks like this array(3) { [0]= array(2) { [0]= string(1) 1 [1]= string(1) 2 } [1]= array(2) { [0]= string(3) 492 [1]= string(3) 211 } [2]= array(2) { [0]= string(2) 11 [1]= string(2) 20 } } I want to loop through so I can get and print 1,492,11 and 2,211,20 What is the best way to do this? I suck with arrays and I can't get my looping right. $a = array(array(1,2), array(492,211), array(11,20) ); for($i=0;$i2;$i++) { foreach($a as $v) { echo $v[$i] . \n; } echo ==\n; } Prints: 1 492 11 == 2 211 20 == -Brian -- s/:-[(/]/:-)/g BrianGnuPG - KeyID: 0x04A4F0DC | Key Server: pgp.mit.edu == gpg --keyserver pgp.mit.edu --recv-keys 04A4F0DC Key Info: http://gfx-design.com/keys Linux Registered User #339825 at http://counter.li.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] arrays question
I have this that looks like this array(3) { [0]= array(2) { [0]= string(1) 1 [1]= string(1) 2 } [1]= array(2) { [0]= string(3) 492 [1]= string(3) 211 } [2]= array(2) { [0]= string(2) 11 [1]= string(2) 20 } } I want to loop through so I can get and print 1,492,11 and 2,211,20 What is the best way to do this? I suck with arrays and I can't get my looping right. Thanks for your help anybody!
Re: [PHP] arrays question
Here's a few loops that should work. You can actually just use the first loop to concatenate text string instead create array items, but I wasn't sure what type of processing you wanted to do with the result. //Convert Array from 3 rows by 2 cols - 2 rows by 3 cols for($i=0; $icount($mainArray); $i++ ) { for ( $x=0; $xcount($mainArray[$i]); $x++ ) { $resultArray[$x][]= $mainArray[$i][$x]; } } Resulting Array Array ( [0] = Array ( [0] = 1 [1] = 492 [2] = 11 ) [1] = Array ( [0] = 2 [1] = 211 [2] = 20 ) ) //Convert array items to text string with , separator for($i=0; $icount($resultArray); $i++) { $resultArray[$i]= ''.implode(',',$resultArray[$i]).''; } Resulting Array: Array ( [0] = 1,492,11 [1] = 2,211,20 ) On Nov 11, 2005, at 3:25 PM, cybermalandro cybermalandro wrote: I have this that looks like this array(3) { [0]= array(2) { [0]= string(1) 1 [1]= string(1) 2 } [1]= array(2) { [0]= string(3) 492 [1]= string(3) 211 } [2]= array(2) { [0]= string(2) 11 [1]= string(2) 20 } } I want to loop through so I can get and print 1,492,11 and 2,211,20 What is the best way to do this? I suck with arrays and I can't get my looping right. Thanks for your help anybody! -- Brent Baisley Systems Architect Landover Associates, Inc. Search Advisory Services for Advanced Technology Environments p: 212.759.6400/800.759.0577 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays
Hi, How can i destroy an array? I mean i have a loop and for each new value in the loop i want to destroy the array. Something like that: while($row = mysql_fetch_array($result)) { $product[] = $product_id; // some code here } I've tried this but doesn't work while($row = mysql_fetch_array($result)) { $product = array(); $product[] = $product_id; // some code here } Any help would be appreciated !!
Re: [PHP] Arrays
Hello, You may try unset($product) in your loop if you want to delete this var. Your code $product=array(); must work too... Another way, must be to use something like this $product[id]=$product_id; But i dont think it's your real goal?! Could you give some more information about that? Olivier Ps: documentation for unset : http://www.php.net/manual/en/function.unset.php Le Mardi 12 Juillet 2005 13:34, [EMAIL PROTECTED] a écrit : Hi, How can i destroy an array? I mean i have a loop and for each new value in the loop i want to destroy the array. Something like that: while($row = mysql_fetch_array($result)) { $product[] = $product_id; // some code here } I've tried this but doesn't work while($row = mysql_fetch_array($result)) { $product = array(); $product[] = $product_id; // some code here } Any help would be appreciated !! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
On 12/07/05, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, How can i destroy an array? I mean i have a loop and for each new value in the loop i want to destroy the array. Something like that: while($row = mysql_fetch_array($result)) { $product[] = $product_id; // some code here } I've tried this but doesn't work while($row = mysql_fetch_array($result)) { $product = array(); $product[] = $product_id; // some code here } To destroy an array? First of all, where does $product_id come from? You gave us no code that gives us that. Second, if you're trying to make an array populated with a feild from each row returned, your first example will work, but not the second. The second example will empty the array, and start a new one (which doesn't make sense to me why you would do that--because in the end, you're only going to have the array with the last row returned). But if you're trying to destroy an array doing either: unset($an_array) or $an_array = array(); will do the job. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Arrays
I guess your purpose is to just save the row data from the mysql to the array each unit. So may be the result that you expected is sth like: $product[0] = 1; $product[1] = 2; $product[2] = 3; .. If you just loop for each new value in the loop and to destroy the array, you second example is okey. Best regards, Shiqi Yang -Original Message- From: Justin Gruenberg [mailto:[EMAIL PROTECTED] Sent: Tuesday, July 12, 2005 7:43 PM To: [EMAIL PROTECTED]; php-general@lists.php.net Subject: Re: [PHP] Arrays On 12/07/05, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, How can i destroy an array? I mean i have a loop and for each new value in the loop i want to destroy the array. Something like that: while($row = mysql_fetch_array($result)) { $product[] = $product_id; // some code here } I've tried this but doesn't work while($row = mysql_fetch_array($result)) { $product = array(); $product[] = $product_id; // some code here } To destroy an array? First of all, where does $product_id come from? You gave us no code that gives us that. Second, if you're trying to make an array populated with a feild from each row returned, your first example will work, but not the second. The second example will empty the array, and start a new one (which doesn't make sense to me why you would do that--because in the end, you're only going to have the array with the last row returned). But if you're trying to destroy an array doing either: unset($an_array) or $an_array = array(); will do the job. -- 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] Arrays not recognized in Simple XML Objects (using print_r)
hi! i'm trying to use the simple_xml functions to get an arrray of data from a sample xml file. here's my sample_data.xml ?xml version=1.0 encoding=ISO-8859-1? sample_data first_names first_nameamit/first_name first_nameamar/first_name /first_names /sample_data the php file ?php $sample_data = simplexml_load_file(sample_data.xml); print_r($sample_data); print_r($sample_data-first_names); print_r($sample_data-first_names-first_name); ? output of $ php test_xml_1.php SimpleXMLElement Object ( [first_names] = SimpleXMLElement Object ( [first_name] = Array ( [0] = amit [1] = amar ) ) ) SimpleXMLElement Object ( [first_name] = Array ( [0] = amit [1] = amar ) ) SimpleXMLElement Object ( [0] = amit ) The above output shows $sample_data-first_names-first_name as an ARRAY in the first 2 print_r 's however when a print_r is run on itself it shows it as a SimpleXMLElementObject. Question is why the last print_r gives different information compared to the other 2. I also tried running $key = array_rand($sample_data-first_names-first_name) and it gives a warning message Warning: array_rand(): First argument has to be an array in /home/yvb/work/practice/php/XML/foo.php on line 16 any clue how do i use the $sample_data-first_names-first_name as an array ? thx. yashesh. -- go pre http://www2.localaccess.com/rlalonde/pre.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
You can absolutely use arrays as form field names. They allow great flexibility. Although you wouldn't use quotes for the array keys. So your form field name would be something like: att[keyname] While in PHP, the same array would look like: $att['keyname'] Your array id's are consider keys since they are not sequential. Just treat them as names for the array entry. There are a number of ways to reference it. $att = $_POST['att']; foreach($att as $attkey=$attval) { echo $att[$attkey]; echo $attval; } Or you could use the array_keys functions to get the keys to the array in it's own array that can be referenced sequentially. $att = $_POST['att']; $attkeys = array_keys($att); echo $att[$attkeys[0]]; echo $att[$attkeys[1]]; etc. You can even use multidimensional arrays as form field names, which is helpful when you need to keep separate form fields related. Like having multiple phone number/phone description fields: input type=text name=phone[home][desc] value=Vacation Home size=10 input type=text name=phone[home][number] value=123456789 size=10 input type=text name=phone[work][desc] value=Uptown Office size=10 input type=text name=phone[work][number] value=123456789 size=10 On Dec 28, 2004, at 10:52 PM, GH wrote: Would it be possible in a form fields name to make it an array? This way it would be i.e. att[$part_id] Now is there a way to iterate through the array when I submit the form to process it, being that the ID numbers are not going to be sequential and that there will be some numbers not included? I.E. the id's would be 1, 5, 6, 7, 20, 43 and how would I refence it? would it be $_POST['att']['[partIDhere}'] ? Thanks G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- Brent Baisley Systems Architect Landover Associates, Inc. Search Advisory Services for Advanced Technology Environments p: 212.759.6400/800.759.0577 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays
Would it be possible in a form fields name to make it an array? This way it would be i.e. att[$part_id] Now is there a way to iterate through the array when I submit the form to process it, being that the ID numbers are not going to be sequential and that there will be some numbers not included? I.E. the id's would be 1, 5, 6, 7, 20, 43 and how would I refence it? would it be $_POST['att']['[partIDhere}'] ? Thanks G -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Hodicska Gergely wrote: trigger_error('Hoppa, egy új típus a PHP-ben? '.__CLASS__.'::'.__FUNCTION__.'()!', E_USER_WARNING); on that line, what is the error you are trying to catch? I can't read what ever language that is ;-) thanks. -Nick Peters -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Hodicska Gergely wrote: Hi! Would this work the same for multidimensional arrays? Encoding was a special feature needed by me, maybe you don't need it. Usage: myArray = array(...); echo 'script'.arrayToJsArray($myArray, 'myArray').'/script'; Felho --- 8 --- arrayToJsArray.php --- 8 --- ? function valueToJsValue($value, $encoding = false) { if (!is_numeric($value)) { $value = str_replace('\\', '', $value); $value = str_replace('', '\', $value); $value = ''.$value.''; } if ($encoding) { switch ($encoding) { case 'utf8' : return iconv(ISO-8859-2, UTF-8, $value); break; } } else { return $value; } } function arrayToJsArray( $array, $name, $nl = \n, $encoding = false ) { if (is_array($array)) { $jsArray = $name . ' = new Array();'.$nl; foreach($array as $key = $value) { switch (gettype($value)) { case 'unknown type': case 'resource': case 'object': break; case 'array': $jsArray .= arrayToJsArray($value, $name.'['.valueToJsValue($key, $encoding).']', $nl); break; case 'NULL': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = null;'.$nl; break; case 'boolean': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.($value ? 'true' : 'false').';'.$nl; break; case 'string': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.valueToJsValue($value, $encoding).';'.$nl; break; case 'double': case 'integer': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.$value.';'.$nl; break; default: trigger_error('Hoppa, egy új típus a PHP-ben? '.__CLASS__.'::'.__FUNCTION__.'()!', E_USER_WARNING); } } return $jsArray; } else { return false; } } ? --- 8 --- arrayToJsArray.php --- 8 --- thanks this works perfect! -- -Nick Peters -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Marek Kilimajer wrote: Nick Peters wrote: Hey, i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: script language=javascript var myarray = new Array(?PHP echo $myarray; ?); /script but it didn't work. Anybody got any ideas? thanks in advance. For integers and floats: var myarray = new Array(?PHP echo implode(', ', $myarray); ?); For strings: var myarray = new Array(?PHP echo ''. implode(', ', $myarray) .''; ?); Would this work the same for multidimensional arrays? -- -Nick Peters -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Nick Peters wrote: Marek Kilimajer wrote: Nick Peters wrote: Hey, i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: script language=javascript var myarray = new Array(?PHP echo $myarray; ?); /script but it didn't work. Anybody got any ideas? thanks in advance. For integers and floats: var myarray = new Array(?PHP echo implode(', ', $myarray); ?); For strings: var myarray = new Array(?PHP echo ''. implode(', ', $myarray) .''; ?); Would this work the same for multidimensional arrays? no -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Hi! Would this work the same for multidimensional arrays? Encoding was a special feature needed by me, maybe you don't need it. Usage: myArray = array(...); echo 'script'.arrayToJsArray($myArray, 'myArray').'/script'; Felho --- 8 --- arrayToJsArray.php --- 8 --- ? function valueToJsValue($value, $encoding = false) { if (!is_numeric($value)) { $value = str_replace('\\', '', $value); $value = str_replace('', '\', $value); $value = ''.$value.''; } if ($encoding) { switch ($encoding) { case 'utf8' : return iconv(ISO-8859-2, UTF-8, $value); break; } } else { return $value; } } function arrayToJsArray( $array, $name, $nl = \n, $encoding = false ) { if (is_array($array)) { $jsArray = $name . ' = new Array();'.$nl; foreach($array as $key = $value) { switch (gettype($value)) { case 'unknown type': case 'resource': case 'object': break; case 'array': $jsArray .= arrayToJsArray($value, $name.'['.valueToJsValue($key, $encoding).']', $nl); break; case 'NULL': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = null;'.$nl; break; case 'boolean': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.($value ? 'true' : 'false').';'.$nl; break; case 'string': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.valueToJsValue($value, $encoding).';'.$nl; break; case 'double': case 'integer': $jsArray .= $name.'['.valueToJsValue($key, $encoding).'] = '.$value.';'.$nl; break; default: trigger_error('Hoppa, egy új típus a PHP-ben? '.__CLASS__.'::'.__FUNCTION__.'()!', E_USER_WARNING); } } return $jsArray; } else { return false; } } ? --- 8 --- arrayToJsArray.php --- 8 --- -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] PHP arrays and javascript
Hey, i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: script language=javascript var myarray = new Array(?PHP echo $myarray; ?); /script but it didn't work. Anybody got any ideas? thanks in advance. -- -Nick Peters -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] PHP arrays and javascript
snip i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: script language=javascript var myarray = new Array(?PHP echo $myarray; ?); /script but it didn't work. Anybody got any ideas? /snip You need to generate the javascript array from your PHP array. Example: In your script create a php array of the values you wish to use. Using indeces is not essential. If you do not use them, you can just use a counter var when you loop through the array to create the indeces for the JS array. ?php $arrayVar = array('first index'='item 1', 'second index'='item 2', 'third index'='item 3'); $jsVar = var myArray = new Array();\n; foreach ($arrayVar as $idx=$val) { $jsVar .= myArray['{$idx}'] = {$val}\n; } ? The final output of this will be: var myArray = new Array(); myArray['first index'] = 'item 1'; myArray['second index'] = 'item 2'; myArray['third index'] = 'item 3'; HTH, Pablo -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP arrays and javascript
Nick Peters wrote: Hey, i know this probally a simple question, but it has been stumping me for quite some time now. How do i pass a php array to a javascript? i tryed: script language=javascript var myarray = new Array(?PHP echo $myarray; ?); /script but it didn't work. Anybody got any ideas? thanks in advance. For integers and floats: var myarray = new Array(?PHP echo implode(', ', $myarray); ?); For strings: var myarray = new Array(?PHP echo ''. implode(', ', $myarray) .''; ?); -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
Ben Miller wrote: edit I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values [the whole array and all of it's values] from page to page and/or store in a db. ? echo (htmlheadtitleArray Example/title/headbody); echo (form action=\.$_SERVER['PHP_SELF'].\ method=\POST\); for ($i=0; $icount($array_variable); $i++){ echo (input name=\array_variable[]\ type=\hidden\ value=\.$array_variable[$i].\); } ##-- Add to the array? echo (input name=\array_variable[]\ type=\text\ value=\\); echo (input name=\submit\ type=\submit\ value=\Add to the Array\); echo (/form); echo (br); echo (Current Array Elements:); for ($i=0; $icount($array_variable); $i++){ echo (BR.$array_variable[$i]); } echo (/body/html); ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
Zareef Ahmed wrote: But you need to do serialize and unserialize in case of array or object. Do :: $val_ar=array(one,two,three); $_SESSION['val_ar_store']=serialize($val_ar); Serialization is done automatically. You don't need to do it yourself. You can even store simple value-objects in the session witout manual serialization. So you can do: $val_ar = array(one, two, three); $_SESSION['val_ar_store'] = $val_ar; serialize/unserialize are useful if you want to store complex data in a file or in a database. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Arrays
I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. ben -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Arrays
edit I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values [the whole array and all of it's values] from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. ben -- 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] Arrays
On Mon, 8 Nov 2004 16:01:16 -0700, Ben [EMAIL PROTECTED] wrote: I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. Where is you (broken) PHP code that you have written so far? What is it not doing that you are expecting it to do? -- Greg Donald Zend Certified Engineer http://gdconsultants.com/ http://destiney.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Arrays
Hi Ben, Welcome to the wonderful world of PHP. Working with array in PHP is very easy. A large number of functions are there. Please visit the manual http://www.phpcertification.com/manual.php/ref.array.html You can move values ( including Arrays) from page to page in session variables. But you need to do serialize and unserialize in case of array or object. Do :: $val_ar=array(one,two,three); $_SESSION['val_ar_store']=serialize($val_ar); Now you can get your array in any page simply $val_ar=unserialize($_SESSION['val_ar_store']); Print_r($val_ar); This process is very simple. Please see manual http://www.phpcertification.com/manual.php/function.serialize.html http://www.phpcertification.com/manual.php/function.unserialize.html Revert back with any other problem. Zareef ahmed -Original Message- From: Ben [mailto:[EMAIL PROTECTED] Sent: Tuesday, November 09, 2004 4:31 AM To: [EMAIL PROTECTED] Subject: [PHP] Arrays I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. ben -- Zareef Ahmed :: A PHP develoepr in Delhi ( India ) Homepage :: http://www.zasaifi.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Arrays
There are a couple of ways to pass arrays (and their values) between pages. I personally would put the array into a session variable ($_SESSION - see reference) and access the various parts as needed. Another option is sending the whole array or it's parts as hidden fields in a form (access with the $_GET and $_POST - again see reference), but that means the user has to click a submit button. If you are trying to store the array in a Database I would suggest you make each element of the array into it's own column of the database. Databases generally should only have 1 piece of information being saved per cell (think excel). If you would like a link to database design, let me know and I will send it. If all you really were asking was how to iterate through an array - then I would recommend looking at the manual's page on arrays ( http://www.php.net/manual/en/language.types.array.php ). Respectfully, Ligaya Turmelle References: http://www.php.net/language.variables.predefined Ben wrote: I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. ben -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Arrays
Thank you to all for help with this. Once I have a general idea of which path to head down, I can figure it out pretty well from there, and you have all given me a pretty good road map. Anyway, thanks again. It is greatly appreciated. I'll let you know hot it all comes out. Ben -Original Message- From: Ligaya Turmelle [mailto:[EMAIL PROTECTED] Sent: Monday, November 08, 2004 10:03 PM To: Ben Cc: [EMAIL PROTECTED] Subject: Re: [PHP] Arrays There are a couple of ways to pass arrays (and their values) between pages. I personally would put the array into a session variable ($_SESSION - see reference) and access the various parts as needed. Another option is sending the whole array or it's parts as hidden fields in a form (access with the $_GET and $_POST - again see reference), but that means the user has to click a submit button. If you are trying to store the array in a Database I would suggest you make each element of the array into it's own column of the database. Databases generally should only have 1 piece of information being saved per cell (think excel). If you would like a link to database design, let me know and I will send it. If all you really were asking was how to iterate through an array - then I would recommend looking at the manual's page on arrays ( http://www.php.net/manual/en/language.types.array.php ). Respectfully, Ligaya Turmelle References: http://www.php.net/language.variables.predefined Ben wrote: I hope this is not a stupid question, but I am learning how to work with Arrays, and am having trouble figuring out how to move array values from page to page and/or store in a db. Once again, I am new to arrays (and fairly new to PHP for that matter), so please don't get too technical in replies. Thanks so much for help. ben -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] arrays() current() next() who to use
I'm setting up an array based on recordset that does a loop as follows: do { //SET ARRAYS $z['username'][$k] = $row_rsUSERIDID['uname']; $z['distance'][$k++] = $totaldist; } while ($row_rsUSERIDID = mysql_fetch_assoc($rsUSERIDID)); //SET NEW ARRAY $z['user'] = $z['username']; //SORT BY DISTANCES natsort ($z['distance']); reset ($z['distance']); foreach($z['distance'] as $k = $v){ $newuser = {$z['user'][$k]}; echo $newuser . br; } How can I now get this output displyed in groups of 10 so that I can display them 10 at a time on a page then click a next button to dispaly they next 10 and so forth? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays() current() next() who to use
From: Vern [EMAIL PROTECTED] How can I now get this output displyed in groups of 10 so that I can display them 10 at a time on a page then click a next button to dispaly they next 10 and so forth? Can't you do all that sorting in your query so you can just retrieve 10 rows at a time using LIMIT? ---John Holmes... UCCASS - PHP Survey System http://www.bigredspark.com/survey.html -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays() current() next() who to use
Problem with that is it sorts according the results of the recordset range. For instance: It will show the user 1 trhough 10 sorted by miles then 20 - 30 sorted by miles, however, in 1 through 10 could have a range of 0 to 1000 miles and the next set will have 5 to 200 miles. What I need is to sort them all by miles first. The only way I know to do that is to do the way I set it up. So if I create an array, sort that array by the miles then use that array. However the array is different that the recordset and thus does not use LIMIT. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays() current() next() who to use
Vern [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Problem with that is it sorts according the results of the recordset range. For instance: It will show the user 1 trhough 10 sorted by miles then 20 - 30 sorted by miles, however, in 1 through 10 could have a range of 0 to 1000 miles and the next set will have 5 to 200 miles. What I need is to sort them all by miles first. The only way I know to do that is to do the way I set it up. So if I create an array, sort that array by the miles then use that array. However the array is different that the recordset and thus does not use LIMIT. What about this: SELECT * FROM table ORDER BY miles LIMIT 0, 10 Then pass the offset to your query function and exchange it with 0: SELECT * FROM table ORDER BY miles LIMIT $offset, 10 Of course you have to properly validate that $offset is an integer before using it in the query. Regards, Torsten Roehr -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] arrays() current() next() who to use
The miles are being caluculated during the loop that is created using the recordset not in the database. First I create a do..while loop to get the miles do { $k = 0; //SET FIRST ARRAY OF ONLINE USERS AND CALCULATE MILES do { //GEOZIP $zip2 = $row_rsUSERIDID['zip']; $coor1=mycoors($zip1); $coor2=mycoors($zip2); $line1=split(\|,$coor1); $line2=split(\|,$coor2); $totaldist=distance($line1[0],$line1[1],$line2[0],$line2[1],mi); //SET NEW ARRAY WITH MILES $z['username'][$k] = $row_rsUSERIDID['uname']; $z['distance'][$k++] = $totaldist; } while ($row_rsUSERIDID = mysql_fetch_assoc($rsUSERIDID)); //SET NEW ARRAY $z['user'] = $z['username']; //SORT BY DISTANCES natsort ($z['distance']); reset ($z['distance']); //DISPLAY USER INFORMATION SORTED BY MILES foreach($z['distance'] as $k = $v){ $newuser = $z['user'][$k]; echo $newuser . - . $v . br; } } while ($row_rsUSERIDID = mysql_fetch_assoc($rsUSERIDID)); I now what to display this info 10 records at a time. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php