Re: [PHP] Array help.
On Wed, Oct 24, 2012 at 2:40 PM, Samuel Lopes Grigolato samuel.grigol...@gmail.com wrote: Could you try changing this: if($groupTest != FALSE) { to this: if($groupTest !== FALSE) { ? Hah. Perfect! Thanks. -Mensagem original- De: Paul Halliday [mailto:paul.halli...@gmail.com] Enviada em: quarta-feira, 24 de outubro de 2012 15:38 Para: PHP-General Assunto: [PHP] Array help. I am processing v4IP's and what I want to do is a prefix substitution if the 3rd octet matches a predefined list $groupMappings. I went down this path and it isn't working as expected. Drawing a blank on this one. Why does 40 miss the comparison? $hostname = Z; $ips = array('10.1.40.1','10.1.41.1','10.1.1.1','10.1.40.1','10.9.1.1'); foreach ($ips as $ip) { $groupMappings = array('40' ='A','41' ='B','1' ='C'); $ocTest = explode(., $ip); $groupKeys = array_keys($groupMappings); $groupTest = array_search($ocTest[2], $groupKeys); if($groupTest != FALSE) { $hostGroup = $groupMappings[$groupKeys[$groupTest]]; echo Hit! $ip : $hostname : $hostGroup\n; } else { $hostGroup = substr($hostname, 0,2); echo Miss! $ip : $hostname : $hostGroup\n; } } Miss! 10.1.40.1 : Z : Z Hit! 10.1.41.1 : Z : B Hit! 10.1.1.1 : Z : C Miss! 10.1.40.1 : Z : Z Hit! 10.9.1.1 : Z : C Thanks! -- Paul Halliday http://www.pintumbler.org/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array help.
From: Paul Halliday [paul.halli...@gmail.com] Sent: 24 October 2012 18:38 To: PHP-General Subject: [PHP] Array help. $groupMappings = array('40' ='A','41' ='B','1' ='C'); $ocTest = explode(., $ip); $groupKeys = array_keys($groupMappings); $groupTest = array_search($ocTest[2], $groupKeys); if($groupTest != FALSE) { I think you're making a little bit of a meal of this. My initial thoughts included pointing you at array_key_exists() (and, why on earth have you got $ocTest[2] in quotes?), but then I realised if I were writing this I'd probably just use isset(), thus: $ocTest = explode(., $ip); if (isset($groupMappings[$ocTest[2]])): // success else: // fail endif; Hope this helps! Cheers! Mike -- Mike Ford, Electronic Information Developer, Libraries and Learning Information Portland PD507, City Campus, Leeds Metropolitan University, Portland Way, LEEDS, LS1 3HE, United Kingdom E: m.f...@leedsmet.ac.uk T: +44 113 812 4730 To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array unset()
Ken Robinson kenrb...@rbnsn.com wrote: At 08:50 PM 9/23/2012, Ron Piggott wrote: I am wondering if there is a way to remove from an array where the value is 0 (âzeroâ) Array example: $total_points_awarded = array( 1 = 17, 3 = 14, 4 = 0, 5 = 1, 6 = 0 ); In this example I would like to remove element # 4 and # 6. The âkeyâ ( 1,3,4,5,6 ) represents the memberâs account #. It is an auto_increment value in a mySQL table The âvalueâ ( 17,14,0,1,0 ) represents their score. The application for this is a list of the top users. If someone has 0 points I donât want to include them. Any thoughts? Any help is appreciated. Look at array_filter() ... http://php.net/array_filter ?php $total_points_awarded = array( 1 = 17, 3 = 14, 4 = 0, 5 = 1, 6 = 0 ); print_r(array_filter($total_points_awarded)); Ken -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Wouldn't it be far easier to do this at the database level in the query? -- Sent from my Android phone with K-9 Mail. Please excuse my brevity. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array unset()
At 08:50 PM 9/23/2012, Ron Piggott wrote: I am wondering if there is a way to remove from an array where the value is 0 (âzeroâ) Array example: $total_points_awarded = array( 1 = 17, 3 = 14, 4 = 0, 5 = 1, 6 = 0 ); In this example I would like to remove element # 4 and # 6. The âkeyâ ( 1,3,4,5,6 ) represents the memberâs account #. It is an auto_increment value in a mySQL table The âvalueâ ( 17,14,0,1,0 ) represents their score. The application for this is a list of the top users. If someone has 0 points I donât want to include them. Any thoughts? Any help is appreciated. Look at array_filter() ... http://php.net/array_filter ?php $total_points_awarded = array( 1 = 17, 3 = 14, 4 = 0, 5 = 1, 6 = 0 ); print_r(array_filter($total_points_awarded)); Ken -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array
On Sat, 2011-12-31 at 14:53 +0100, saeed ahmed wrote: how can you explain someone in a simplest and everyday use example of ARRAY. The manual page explains it pretty succinctly. I don't think you'll get more simple than this, as there is obvious prerequisite knowledge assumed (i.e. that you know what a simple variable is, etc) -- Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array
how can you explain someone in a simplest and everyday use example of ARRAY. The manual page explains it pretty succinctly. I don't think you'll get more simple than this, as there is obvious prerequisite knowledge assumed (i.e. that you know what a simple variable is, etc) Hi saeed, Ash means this: http://www.php.net/manual/en/language.types.array.php See the examples in grey-colored boxes. Arrays are just a collection of things. Similar to when you assign one variable one value.. well with an array you assign many variables one value each. But the reason you use an array is that instead of a bunch of separate variables, you want those variables to be part of a collection.. i.e. all those variables have something in common.. like for example you might use one array to describe the parts of a car, and another array to describe all the fruits in your kitchen. You could do this: (all separate independent variables) $part1 = 'spark plug'; $part2 = 'rear-view mirror'; $part3 = 'steering wheel'; etc. $fruit1 = 'apple'; $fruit2 = 'banana'; $fruit3 = 'orange'; etc. ...but (depending on your application, and the logic you use), it might make more sense to do something like this instead: (make arrays!) (these, below, are arrays where the key is just a number which is automatically assigned. You can also use another syntax (see the manual) to make arrays where you generate your own custom keys, and those keys can be strings instead of numbers.) $arrParts = array('spark plug', 'rear-view mirror', 'steering wheel'); $arrFruits = array('apple', 'banana', 'orange'); To use the arrays, there are tons of functions: http://www.php.net/manual/en/ref.array.php :-) -Govinda -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array has `trailing comma`, why not the same for function parameter list?
On Sun, Oct 30, 2011 at 08:47, Nam Gi VU nam.gi...@gmail.com wrote: It is convenient to have a trailing comma when defining an array - so as easy to add/remove code to add/remove an entry to the array array( 'key00' = 'value00', 'key01' = 'value01', 'key02' = 'value02', ... ) I suggest to PHP Development team to make it available in the syntax to have a leading comma array( ... , 'key00' = 'value00' , 'key01' = 'value01' , 'key02' = 'value02' ) in such way, we can thought of the leading commas as the list bulletings. And the same things would be lovely to be applied also to function parameter list. I don't see why not :) What do you thing about my suggestion? Hope to hear from you! For feature requests such as this, please discuss it on the Internals list (CC'd on this email) and suggest it via the bug tracker at https://bugs.php.net/ (with the bug type as a Feature/Change Request). -- /Daniel P. Brown Network Infrastructure Manager http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array has `trailing comma`, why not the same for function parameter list?
On Sun, Oct 30, 2011 at 8:47 AM, Nam Gi VU nam.gi...@gmail.com wrote: It is convenient to have a trailing comma when defining an array - so as easy to add/remove code to add/remove an entry to the array array( 'key00' = 'value00', 'key01' = 'value01', 'key02' = 'value02', ... ) I suggest to PHP Development team to make it available in the syntax to have a leading comma array( ... , 'key00' = 'value00' , 'key01' = 'value01' , 'key02' = 'value02' ) in such way, we can thought of the leading commas as the list bulletings. And the same things would be lovely to be applied also to function parameter list. I don't see why not :) What do you thing about my suggestion? Hope to hear from you! WRT functions: while I could see how this would seem like a good idea because of the symmetry in what's going on at a very high level of abstraction, I would be against including it in a language. I don't particularly like it for arrays, but it does make it easy to add items into an array, which happens pretty often in development, especially when writing exploratory code. Function signatures, on the other hand, probably aren't changing nearly as often. At the very least, I wouldn't want to encourage people to make functions with many parameters, as it's normally a sign of poor design. This wouldn't explicitly do so, but would do so implicitly as it's only real purpose is to make it easier to add things. As far as the supporting-a-leading-comma thing goes, I'm pretty ambivalent on it. I don't really like the style outside of Haskell code, but that's just a preference. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array problem
The function fgetcsv() returns an array. http://php.net/manual/en/function.fgetcsv.php On Fri, Sep 9, 2011 at 9:00 AM, Marc Fromm marc.fr...@wwu.edu wrote: I am reading a csv file into an array. The csv file. users.csv file contents: w12345678,a w23456789,b w34567890,c $csvfilename = users.csv; $handle = fopen($csvfilename, r); if($handle) { while (($line = fgetcsv($handle, 1000, ,)) !== FALSE) { $arrUsers[] = $line; } fclose($handle); } When I echo out the elements in the elements in the array $arrUsers I get: Array Array Array foreach ($arrUsers as $user){ echo $user . br /; } I can't figure out why the word Array is replacing the actual data.
Re: [PHP] array problem
On Fri, 2011-09-09 at 16:00 +, Marc Fromm wrote: I am reading a csv file into an array. The csv file. users.csv file contents: w12345678,a w23456789,b w34567890,c $csvfilename = users.csv; $handle = fopen($csvfilename, r); if($handle) { while (($line = fgetcsv($handle, 1000, ,)) !== FALSE) { $arrUsers[] = $line; } fclose($handle); } When I echo out the elements in the elements in the array $arrUsers I get: Array Array Array foreach ($arrUsers as $user){ echo $user . br /; } I can't figure out why the word Array is replacing the actual data. Try print_r($arrUsers); also, the $line is an array of the CSV, so you're storing an array, within the array $arrUsers. foreach ($arrUsers as $user){ foreach ($user as $val) { echo $val . br /; } echo 'hr /'; } -- Steve Staples Web Application Developer 519.258.2333 x8414 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array problem
hi, try to use print_r or var_dump to echo compound data type
Re: [PHP] array problem
You are echoing out an array. If you use something like print_r() or var_dump() you will see the array elements Thanks, Ash http://www.ashleysheridan.co.uk -- Sent from my Android phone with K-9 Mail. Please excuse my brevity. Marc Fromm marc.fr...@wwu.edu wrote: I am reading a csv file into an array. The csv file. users.csv file contents: w12345678,a w23456789,b w34567890,c $csvfilename = users.csv; $handle = fopen($csvfilename, r); if($handle) { while (($line = fgetcsv($handle, 1000, ,)) !== FALSE) { $arrUsers[] = $line; } fclose($handle); } When I echo out the elements in the elements in the array $arrUsers I get: Array Array Array foreach ($arrUsers as $user){ echo $user . br /; } I can't figure out why the word Array is replacing the actual data.
Re: [PHP] Array from one form to other?
On Feb 19, 2011, at 6:38 PM, Yogesh wrote: I have two forms. One form helps read an input file into an array. And the other form needs this array as an input. I am able to read the input file into an array, but how do I pass it over to the other form. Both forms have PHP file as 'action'. I don't entirely understand this; Dan Brown gave you solution to use curl to pass the array to the second form (do you mean script here?). That would certainly work, but I'm wondering if it wouldn't be more secure to spool out the array to a file from the first script after it has processed it, and then read it in to the second script when it starts. This assumes the two scripts are running on the same server, of course. The second script could be called after the first script finishes by using a header redirect. I'm curious about people's thought on the security and efficacy of different ways of sharing data between scripts when you're not using sessions. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array from one form to other?
Hi Tamara, I don't entirely understand this; Dan Brown gave you solution to use curl to pass the array to the second form (do you mean script here?). That would certainly work, but I'm wondering if it wouldn't be more secure to spool out the array to a file from the first script after it has processed it, and then read it in to the second script when it starts. This assumes the two scripts are running on the same server, of course. The second script could be called after the first script finishes by using a header redirect. I'm curious about people's thought on the security and efficacy of different ways of sharing data between scripts when you're not using sessions. I am quite new to PHP. (I am having trouble to understand how HTML, PHP and Javascript work together). Right now I just wanted to get the job done. But if you can suggest me a more efficient way to do it, I will definitely look into it. Thanks, -Yogesh
Re: [PHP] Array from one form to other?
On Feb 20, 2011, at 10:51 AM, Yogesh wrote: I don't entirely understand this; Dan Brown gave you solution to use curl to pass the array to the second form (do you mean script here?). That would certainly work, but I'm wondering if it wouldn't be more secure to spool out the array to a file from the first script after it has processed it, and then read it in to the second script when it starts. This assumes the two scripts are running on the same server, of course. The second script could be called after the first script finishes by using a header redirect. I'm curious about people's thought on the security and efficacy of different ways of sharing data between scripts when you're not using sessions. I am quite new to PHP. (I am having trouble to understand how HTML, PHP and Javascript work together). Right now I just wanted to get the job done. But if you can suggest me a more efficient way to do it, I will definitely look into it. Are you also new to programming in general? If so, I suggest spending some time studying up on programming concepts and design patterns. I do understand the idea of just get the job done, but without basic knowledge, the result is not going to be very good, and likely lead to maintenance nightmares down the road. As I don't really understand what it is you're trying to do, it's hard to make concrete suggestions. From your very brief description, it sounds like you have one script that takes the form submission and populates an array, which you want to share with another script. Typically, data sharing between scripts is accomplished in a few different ways: 1) use of session variables (which requires the script to invoke session management) B) storing the information in a persistent data base (e.g. MySQL) iii) storing the information in a transient data store (e.g. a temporary file). There are different ways to format the data in the file, including as php script (so you can include the file), JSON, YAML, etc. d) passing the information to the second script via a query string or a post data buffer Any of these things require understanding of the mechanisms and implementation idioms involved. Choosing a particular implementation depends on several variables in your overall design and implementation environment. A mailing list is a poor way to transmit this information, which is why most of it is documented elsewhere.
Re: [PHP] Array from one form to other?
On Sat, Feb 19, 2011 at 19:38, Yogesh yogesh...@gmail.com wrote: Hello, I have two forms. One form helps read an input file into an array. And the other form needs this array as an input. I am able to read the input file into an array, but how do I pass it over to the other form. Both forms have PHP file as 'action'. What's the method? GET or POST? -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array from one form to other?
POST On Sat, Feb 19, 2011 at 9:44 PM, Daniel Brown danbr...@php.net wrote: On Sat, Feb 19, 2011 at 19:38, Yogesh yogesh...@gmail.com wrote: Hello, I have two forms. One form helps read an input file into an array. And the other form needs this array as an input. I am able to read the input file into an array, but how do I pass it over to the other form. Both forms have PHP file as 'action'. What's the method? GET or POST? -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/
Re: [PHP] Array from one form to other?
On Sat, Feb 19, 2011 at 21:50, Yogesh yogesh...@gmail.com wrote: POST Use cURL, look into curl_setopt(), and add square brackets (and optional key names) to your array. A quick start: ?php $ch = curl_init(); curl_setopt(CURLOPT_POST,1); curl_setopt(CURLOPT_POSTFIELDS,'firstArr[]=applefirstArr[]=orangefirstArr[]=bananasecondArr[one]=foosecondArr[two]=bar'); // etc. ? -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array to var - with different name
Paul M Foster wrote: [snip] Shawn, I don't know if I have a good reason, other than I rather like working with string vars instead of array vars from $_REQUEST for (sticky forms and conditionals). I can check/verify them as well in the process. You should probably get used to dealing with the array variables. However, you can also look at the extract() function. It won't do exactly what you want, but it will pull the array keys/values into the current symbol table. Use with caution (note the second parameter to the function). Paul Well, It occurs to me that you can't code in PHP without getting use to dealing with arrays. ;-) I just much rather like typing: input name=f_email value=?PHP if (isset($t_email)) { print htmlspecialchars($t_email);} ? / Instead of: input name=f_email value=?PHP if (isset($_GET['f_email'])) { print htmlspecialchars($_GET['f_email']);} ? / or if ($t_ok) { } instead of: if ($_GET['f_ok']) { } Save's a lot of typing time as far as I can tell. Donovan -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array to var - with different name
Donovan Brooke wrote: [snip] if ($t_ok) { } Small correction.. with my established naming convention.. the above ideally would be: if ($b_ok) { } D -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array to var - with different name
On Thursday 20 January 2011, Donovan Brooke li...@euca.us wrote: Hello again! I'm trying to find a good way to convert array key/value's to variable name values... but with the caveat of the name being slightly different than the original key (to fit my naming conventions). first, I (tediously) did this: --- if (isset($_GET['f_action'])) { $t_action = $_GET['f_action']; } if (isset($_POST['f_action'])) { $t_action = $_POST['f_action']; } if (isset($_GET['f_ap'])) { $t_ap = $_GET['f_ap']; } if (isset($_POST['f_ap'])) { $t_ap = $_POST['f_ap']; } --- Instead, I wanted to find *all* incoming f_ keys in the POST/GET array, and convert them to a variable name consisting of t_ in one statement. That was ver tedious... I then did this test and it appears to work (sorry for email line breaks): - $a_formvars = array('f_1' = '1','f_2' = '2','f_3' = '3','f_4' = '4','f_5' = '5','f_6' = '6',); $t_string = ; foreach ($a_formvars as $key = $value) { if (substr($key,0,2) == 'f_') { $t_string = $t_string . t_ . substr($key,2) . =$value; parse_str($t_string); } } - I figure I can adapt the above by doing something like: $a_formvars = array_merge($_POST,$_GET); However, I thought I'd check with you all to see if there is something I'm missing. I don't speak PHP that well and there may be an easier way. Did you tried the $_REQUEST variable? Take a look on: ?php echo var_dump($_REQUEST); ? Thanks, Donovan Best regards, -- Daniel Molina Wegener dmw [at] coder [dot] cl System Programmer Web Developer Phone: +56 (2) 979-0277 | Blog: http://coder.cl/
Re: [PHP] array to var - with different name
On Thu, Jan 20, 2011 at 2:28 PM, Donovan Brooke wrote: Hello again! I'm trying to find a good way to convert array key/value's to variable name values... but with the caveat of the name being slightly different than the original key (to fit my naming conventions). first, I (tediously) did this: --- if (isset($_GET['f_action'])) { $t_action = $_GET['f_action']; } if (isset($_POST['f_action'])) { $t_action = $_POST['f_action']; } if (isset($_GET['f_ap'])) { $t_ap = $_GET['f_ap']; } if (isset($_POST['f_ap'])) { $t_ap = $_POST['f_ap']; } --- Instead, I wanted to find *all* incoming f_ keys in the POST/GET array, and convert them to a variable name consisting of t_ in one statement. I then did this test and it appears to work (sorry for email line breaks): - $a_formvars = array('f_1' = '1','f_2' = '2','f_3' = '3','f_4' = '4','f_5' = '5','f_6' = '6',); $t_string = ; foreach ($a_formvars as $key = $value) { if (substr($key,0,2) == 'f_') { $t_string = $t_string . t_ . substr($key,2) . =$value; parse_str($t_string); } } - I figure I can adapt the above by doing something like: $a_formvars = array_merge($_POST,$_GET); However, I thought I'd check with you all to see if there is something I'm missing. I don't speak PHP that well and there may be an easier way. Thanks, Donovan -- D Brooke foreach ($_GET as $key = $value) $$key = $value; foreach ($_POST as $key = $value) $$key = $value; or foreach ($_REQUEST as $key = $value) $$key = $value; short-circuited one-liners :) Regards, Tommy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array to var - with different name
On Thu, Jan 20, 2011 at 3:09 PM, Tommy Pham tommy...@gmail.com wrote: On Thu, Jan 20, 2011 at 2:28 PM, Donovan Brooke wrote: Hello again! I'm trying to find a good way to convert array key/value's to variable name values... but with the caveat of the name being slightly different than the original key (to fit my naming conventions). first, I (tediously) did this: --- if (isset($_GET['f_action'])) { $t_action = $_GET['f_action']; } if (isset($_POST['f_action'])) { $t_action = $_POST['f_action']; } if (isset($_GET['f_ap'])) { $t_ap = $_GET['f_ap']; } if (isset($_POST['f_ap'])) { $t_ap = $_POST['f_ap']; } --- Instead, I wanted to find *all* incoming f_ keys in the POST/GET array, and convert them to a variable name consisting of t_ in one statement. I then did this test and it appears to work (sorry for email line breaks): - $a_formvars = array('f_1' = '1','f_2' = '2','f_3' = '3','f_4' = '4','f_5' = '5','f_6' = '6',); $t_string = ; foreach ($a_formvars as $key = $value) { if (substr($key,0,2) == 'f_') { $t_string = $t_string . t_ . substr($key,2) . =$value; parse_str($t_string); } } - I figure I can adapt the above by doing something like: $a_formvars = array_merge($_POST,$_GET); However, I thought I'd check with you all to see if there is something I'm missing. I don't speak PHP that well and there may be an easier way. Thanks, Donovan -- D Brooke foreach ($_GET as $key = $value) $$key = $value; foreach ($_POST as $key = $value) $$key = $value; or foreach ($_REQUEST as $key = $value) $$key = $value; short-circuited one-liners :) Regards, Tommy akk... wrong clicked before I had a chance to fix the code. anyway, foreach ($_GET as $key = $value) if (substr($key, 0, 2) == 'f_') ${'t_'.substr($key, 2)} = $value; -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array to var - with different name
Tommy Pham wrote: [snip] foreach ($_REQUEST as $key = $value) $$key = $value; short-circuited one-liners :) Regards, Tommy akk... wrong clicked before I had a chance to fix the code. anyway, foreach ($_GET as $key = $value) if (substr($key, 0, 2) == 'f_') ${'t_'.substr($key, 2)} = $value; Tommy, excellent.. I had just rewrote your first suggestion: foreach ($a_formvars as $key = $value) ${str_replace('f_', 't_',$key)} = $value; (which works) but I like that you are only affecting the vars that *begin* with $match. I suppose the above would also work with $_REQUEST. Shawn, I don't know if I have a good reason, other than I rather like working with string vars instead of array vars from $_REQUEST for (sticky forms and conditionals). I can check/verify them as well in the process. Thanks to all that posted.. I always learn from the skin the cat game. Donovan -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] array to var - with different name
-Original Message- From: Donovan Brooke [mailto:li...@euca.us] Sent: Thursday, January 20, 2011 3:29 PM Cc: php-general@lists.php.net Subject: Re: [PHP] array to var - with different name Tommy Pham wrote: [snip] foreach ($_REQUEST as $key = $value) $$key = $value; short-circuited one-liners :) Regards, Tommy akk... wrong clicked before I had a chance to fix the code. anyway, foreach ($_GET as $key = $value) if (substr($key, 0, 2) == 'f_') ${'t_'.substr($key, 2)} = $value; Tommy, excellent.. I had just rewrote your first suggestion: foreach ($a_formvars as $key = $value) ${str_replace('f_', 't_',$key)} = $value; (which works) but I like that you are only affecting the vars that *begin* with $match. I suppose the above would also work with $_REQUEST. Shawn, I don't know if I have a good reason, other than I rather like working with string vars instead of array vars from $_REQUEST for (sticky forms and conditionals). I can check/verify them as well in the process. Thanks to all that posted.. I always learn from the skin the cat game. Donovan -- D Brooke I advice strongly against str_replace if you're looking specifically 'f_' at the __beginning__ of the string. substr would guarantee it. Regards, Tommy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On 12 January 2011 20:23, sono...@fannullone.us wrote: Thanks for all the responses to my suggestion. I realize this would be a major change, so that's why I also mentioned it as an addition to the language. I'm sure it's just what you're used to, but still being new to all this, it just makes sense (to me anyway) to have different symbols for different variable types: $scalar @array #hash Since the @ sign is already reserved, maybe there's another symbol that would work better? I don't know. These are just ideas that I came up with while reading and I thought I'd throw it out there to see what others thought. I like the idea of a naming convention, so that's what I'll do in my scripts. I also appreciate the heads up on is_string(), is_array(), and var_dump(). Thanks again, Marc PHP recently introduced namespaces to PHP5. One of the issues at the time was the namespace separator. Do to all the common symbols already being used, it was necessary to re-use one and the context dictates its intent. So whilst \n is the newline character, in the namespace string below namespace my\namespaces\are\here; the \n is not a newline. With that, there are no common symbols available. The Hungarian Notation [1] was what I was taught all those years ago when I learnt standard C programming. I've kept that with me through to PHP. Some say it is redundant in PHP. I suppose this is true, but it works for me and doesn't really get in the way. One thing to remember though is that PHP is a loosely typed language. Having a mechanism which would somehow enforce the type based upon a symbol would certainly be a different way of working for PHP. This is mentioned in the [2] and is suggested to be a poor way of working due to the lack of symbols in general. Regards, Richard. [1] http://en.wikipedia.org/wiki/Hungarian_notation [2] http://en.wikipedia.org/wiki/Hungarian_notation#Relation_to_sigils -- Richard Quadling Twitter : EE : Zend @RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Thu, Jan 13, 2011 at 2:23 AM, Richard Quadling rquadl...@gmail.comwrote: The Hungarian Notation [1] was what I was taught all those years ago when I learnt standard C programming. I learned it early on as well, and I never really liked it. Instead of $iFish I would prefer a more descriptive name such as $fishCount. Sure, it's a little longer to type, but it tells you what that number measures. In today's world of objects and loosely-typed languages, a descriptive variable name can be more important than a symbol or notation to hint at the type. As for arrays, I always name the variable plural. And if it maps keys to values instead of holding a list of items, I will typically name it $foosByBar, e.g. $customersById. From that name I *know* it's array already--no need for a prefix or special symbol. $oPlayer, $sName, $iWidth...what's the point? The context in which the variable is used can provide more meaning. If you stick to short functions/methods that do one specific thing, you'll be able to tell that $player is an object, $name is a string, and $width is an integer. I highly recommend the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. [1] It has a lot of great advice on keeping your code easy to understand, test, and maintain. David [1] http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
Re: [PHP] Array Symbol Suggestion
On Thu, Jan 13, 2011 at 12:59 PM, David Harkness davi...@highgearmedia.com wrote: On Thu, Jan 13, 2011 at 2:23 AM, Richard Quadling rquadl...@gmail.comwrote: The Hungarian Notation [1] was what I was taught all those years ago when I learnt standard C programming. I learned it early on as well, and I never really liked it. Instead of $iFish I would prefer a more descriptive name such as $fishCount. What info did you get on hook for the client? Sure, it's a little longer to type, but it tells you what that number measures. In today's world of objects and loosely-typed languages, a descriptive variable name can be more important than a symbol or notation to hint at the type. As for arrays, I always name the variable plural. And if it maps keys to values instead of holding a list of items, I will typically name it $foosByBar, e.g. $customersById. From that name I *know* it's array already--no need for a prefix or special symbol. $oPlayer, $sName, $iWidth...what's the point? The context in which the variable is used can provide more meaning. If you stick to short functions/methods that do one specific thing, you'll be able to tell that $player is an object, $name is a string, and $width is an integer. I highly recommend the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. [1] It has a lot of great advice on keeping your code easy to understand, test, and maintain. David [1] http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 -- Sometimes...my mama...says I get over excited about technology. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Thu, Jan 13, 2011 at 10:07 AM, David Hutto smokefl...@gmail.com wrote: On Thu, Jan 13, 2011 at 12:59 PM, David Harkness I learned it early on as well, and I never really liked it. Instead of $iFish I would prefer a more descriptive name such as $fishCount. What info did you get on hook for the client? The brain is so interesting. I have no idea where $iFish came from. I've never done an application even remotely related to fishing or the fishing industry. Not even a fish-based game. :) David
Re: [PHP] Array Symbol Suggestion
sono...@fannullone.us wrote: I'd like to make a suggestion for a change, or possibly an addition, to the PHP language. I'm learning PHP and have been very excited with what it can do in relation to HTML. But when I got to the part about arrays, I was disappointed to see that they are designated with a $ the same as other variables. I was learning Perl before I switched, and it uses the @ sign to designate an array. That makes it a lot simpler to see at a glance what is an array and what isn't - at least for beginners like me. Has there been any talk of adopting the @ sign for arrays in PHP? Or is that symbol used for something else that I haven't read about yet? What is the proper channel for making suggestions like this? The php-development mailing list. What you're suggesting is a pretty fundamental change, don't be disappointed if it is not met with universal approval. -- Per Jessen, Zürich (5.9°C) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
sono...@fannullone.us wrote: I'd like to make a suggestion for a change, or possibly an addition, to the PHP language. I'm learning PHP and have been very excited with what it can do in relation to HTML. But when I got to the part about arrays, I was disappointed to see that they are designated with a $ the same as other variables. I was learning Perl before I switched, and it uses the @ sign to designate an array. That makes it a lot simpler to see at a glance what is an array and what isn't - at least for beginners like me. Has there been any talk of adopting the @ sign for arrays in PHP? Or is that symbol used for something else that I haven't read about yet? What is the proper channel for making suggestions like this? Thanks, Marc Hi Marc, I'm a PHP n00b as well and had similar thoughts regarding this.. just imagine two variables called the same thing.. a string and array.. and accidentally resetting one.. $oops = something; however, from my experience, there is often this kind of problem in any language, and that is where naming conventions come in very handy. I don't know if the PHP community has any standard convention.. but I would suggest something like: $a_foo (for arrays) $f_foo (imploding into form variables) $s_foo (string variables) $db_foo (variables coming from databases perhaps) etc.. This way, you'd never be confused of the origin of the variable. Donovan -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Wed, 2011-01-12 at 11:45 -0800, sono...@fannullone.us wrote: I'd like to make a suggestion for a change, or possibly an addition, to the PHP language. I'm learning PHP and have been very excited with what it can do in relation to HTML. But when I got to the part about arrays, I was disappointed to see that they are designated with a $ the same as other variables. I was learning Perl before I switched, and it uses the @ sign to designate an array. That makes it a lot simpler to see at a glance what is an array and what isn't - at least for beginners like me. Has there been any talk of adopting the @ sign for arrays in PHP? Or is that symbol used for something else that I haven't read about yet? What is the proper channel for making suggestions like this? Thanks, Marc PHP is a loosely typed language, so you can have a variable that, throughout its lifetime in an app, is both a scaler (integer, string, etc) or an array. For example: ?php $message = hello world; echo $message; $message = array('hello', 'bob'); echo {$message[0]} {$message[1]}; ? There are functions you can use to determine the type of a variable, such as is_string() and is_array() and you can use var_dump() in debug statements to quickly see the type of a variable. I think changing something as integral as a variable prefix would break a lot of code which makes use of the loose typing, and would cause much more confusion further down the line. Also, as you may have guessed, the @ symbol is already in use at the moment. In PHP it ensures that minor errors are silently ignored. For example: @executeSomeFunction() would run that named function, but ignore any minor errors and warnings. You'll typically find it used a lot in calls to mail() as that can be flaky on some systems due to a number of factors outside of PHP. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Array Symbol Suggestion
On Jan 12, 2011, at 3:28 PM, Ashley Sheridan wrote: If you check out the manual pages for those functions as well, you'll see other related functions. I must say, of any language I've used, the php.net documentation is by far the best, giving plenty of information and user comments too. It's a resource I still can't do without, and I reckon even the old hands on this list would say the same. Thanks, Ash http://www.ashleysheridan.co.uk I fully agree with you on php.net being some of the best documentation out there. I would say that a lot of the Java documentation is wonderfully done as well. It doesn't offer user comments, but it is very complete and covers just about every aspect of a class. Regards, -Josh Joshua Kehn | josh.k...@gmail.com http://joshuakehn.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Wed, Jan 12, 2011 at 14:45, sono...@fannullone.us wrote: I'd like to make a suggestion for a change, or possibly an addition, to the PHP language. I'm learning PHP and have been very excited with what it can do in relation to HTML. But when I got to the part about arrays, I was disappointed to see that they are designated with a $ the same as other variables. I was learning Perl before I switched, and it uses the @ sign to designate an array. That makes it a lot simpler to see at a glance what is an array and what isn't - at least for beginners like me. Has there been any talk of adopting the @ sign for arrays in PHP? Or is that symbol used for something else that I haven't read about yet? The @ is an error control operator, used to buffer the output and store it in a variable - $php_errormsg. There's no way that would be changed to become an array designator (though that doesn't mean your idea itself is a bad one). What is the proper channel for making suggestions like this? Usually on the Internals mailing list (intern...@lists.php.net) or as a Feature Request in the bug tracker (http://bugs.php.net/). -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Wed, Jan 12, 2011 at 12:37 PM, Daniel Brown danbr...@php.net wrote: The @ is an error control operator, used to buffer the output and store it in a variable - $php_errormsg. There's no way that would be changed to become an array designator (though that doesn't mean your idea itself is a bad one). @ squelches error messages. AFAIK $php_errormsg is the last error that PHP incurred. not based on @ @ just silences the errors from being reported, which is a bad thing as error collection is done even if error_reporting is off, it is still built internally as a string, that's why developing with E_ALL and E_STRICT even on is the best practice. even notices wind up adding to the internal error/etc. string stack. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
On Wed, Jan 12, 2011 at 15:41, Michael Shadle mike...@gmail.com wrote: On Wed, Jan 12, 2011 at 12:37 PM, Daniel Brown danbr...@php.net wrote: The @ is an error control operator, used to buffer the output and store it in a variable - $php_errormsg. There's no way that would be changed to become an array designator (though that doesn't mean your idea itself is a bad one). @ squelches error messages. AFAIK $php_errormsg is the last error that PHP incurred. not based on @ Correct. The way I worded it makes it sound like @ is what populates the variable, which would be incorrect. Plus, I should also mention that $php_errormsg is only available if you enable track_errors anyway, which (if I remember correctly) is off by default. Thanks for pointing that out, Mike. -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
Ashley Sheridan wrote: On Wed, 2011-01-12 at 12:23 -0800, sono...@fannullone.us wrote: Thanks for all the responses to my suggestion. I realize this would be a major change, so that's why I also mentioned it as an addition to the language. I'm sure it's just what you're used to, but still being new to all this, it just makes sense (to me anyway) to have different symbols for different variable types: $scalar @array #hash Since the @ sign is already reserved, maybe there's another symbol that would work better? I don't know. These are just ideas that I came up with while reading and I thought I'd throw it out there to see what others thought. I like the idea of a naming convention, so that's what I'll do in my scripts. I also appreciate the heads up on is_string(), is_array(), and var_dump(). Thanks again, Marc If you check out the manual pages for those functions as well, you'll see other related functions. I must say, of any language I've used, the php.net documentation is by far the best, giving plenty of information and user comments too. It's a resource I still can't do without, and I reckon even the old hands on this list would say the same. Yes, I wouldn't want to be without my local php.net mirror. Other languages that can easily match the quality of the documentation - assembler, C and C++, to name a few. -- Per Jessen, Zürich (7.9°C) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array Symbol Suggestion
Donovan Brooke wrote: however, from my experience, there is often this kind of problem in any language, and that is where naming conventions come in very handy. I don't know if the PHP community has any standard convention.. One popular naming convention: http://en.wikipedia.org/wiki/Hungarian_notation -- Per Jessen, Zürich (7.8°C) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array question
Jim Lucas has it. You can use the preg_match function to find it. I would use regexp for that reason. regexp is good for making sure things are typed the way they need to (mostly used for). Ravi. On Sat, Dec 18, 2010 at 5:17 PM, Jim Lucas li...@cmsws.com wrote: On 12/17/2010 12:52 PM, Sorin Buturugeanu wrote: Hello all! I have a question regarding arrays and the way I can use a value. Let's say I have this string: $s = 'banana,apple,mellon,grape,nut,orange' I want to explode it, and get the third value. For this I would normally do: $a = explode(',', $s); echo $s[2]; That's all fine, but is there a way to get the value directly, without having to write another line in my script. I mean something like this: echo explode(',', $s)[2]; or echo {explode(',', $s)}[2]; I couldn't find out this answer anywhere, that's why I posted here. Cheers and thanks! Sure it CAN be done. Nobody laugh too loud here... But... ?php $s = 'banana,apple,mellon,grape,nut,orange'; echo preg_replace('/([^,]+,){3}([^,]+).*/', '$2', $s); ? Outputs: grape The {3} part is equivalent to the array position. Change that number, and you change which word will get displayed. Jim Lucas -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array question
On 12/17/2010 12:52 PM, Sorin Buturugeanu wrote: Hello all! I have a question regarding arrays and the way I can use a value. Let's say I have this string: $s = 'banana,apple,mellon,grape,nut,orange' I want to explode it, and get the third value. For this I would normally do: $a = explode(',', $s); echo $s[2]; That's all fine, but is there a way to get the value directly, without having to write another line in my script. I mean something like this: echo explode(',', $s)[2]; or echo {explode(',', $s)}[2]; I couldn't find out this answer anywhere, that's why I posted here. Cheers and thanks! Sure it CAN be done. Nobody laugh too loud here... But... ?php $s = 'banana,apple,mellon,grape,nut,orange'; echo preg_replace('/([^,]+,){3}([^,]+).*/', '$2', $s); ? Outputs: grape The {3} part is equivalent to the array position. Change that number, and you change which word will get displayed. Jim Lucas -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] array question
[snip] I have a question regarding arrays and the way I can use a value. Let's say I have this string: $s = 'banana,apple,mellon,grape,nut,orange' I want to explode it, and get the third value. For this I would normally do: $a = explode(',', $s); echo $s[2]; That's all fine, but is there a way to get the value directly, without having to write another line in my script. I mean something like this: echo explode(',', $s)[2]; or echo {explode(',', $s)}[2]; I couldn't find out this answer anywhere, that's why I posted here. [/snip] Because the array is not formed until after the explode you cannot do it with one command, but you could place 2 commands on one line :) $a = explode(',', $s); echo $a[2]; -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array question
On Fri, Dec 17, 2010 at 15:52, Sorin Buturugeanu m...@soin.ro wrote: Hello all! I have a question regarding arrays and the way I can use a value. Let's say I have this string: $s = 'banana,apple,mellon,grape,nut,orange' I want to explode it, and get the third value. For this I would normally do: $a = explode(',', $s); echo $s[2]; That's all fine, but is there a way to get the value directly, without having to write another line in my script. I mean something like this: echo explode(',', $s)[2]; or echo {explode(',', $s)}[2]; I couldn't find out this answer anywhere, that's why I posted here. Unfortunately, no --- at least, not yet. Chaining discussions come up now and again, so it's quite possible that future versions of PHP will have something similar. That said, for now you could do something like this: ?php /** * mixed return_item( string $car, mixed $pos ) * - $str The original string * - $charThe delimiting character(s) by which to explode * - $pos The position to return * - $shift Whether or not we should see 1 as the first array position */ function return_item($str,$char,$pos=null,$shift=false) { // Make sure $char exists in $str, return false if not. if (!strpos($str,$char)) return false; // Split $char by $str into the array $arr $arr = explode($char,$str); // If $pos undefined or null, return the whole array if (is_null($pos)) return $arr; // If $pos is an array, return the requested positions if (isset($pos) is_array($pos) !empty($pos)) { // Instantiate a second array container for return $ret = array(); // Iterate foreach ($pos as $i) { // This is just in case it was given screwy or a number as a non-integer if (!is_int($i) is_numeric($i)) $i = (int)round($i); // Make sure $i is now an integer and that position exists if (!is_int($i) || !isset($arr[$i]) || empty($arr[$i])) continue; // If all seems okay, append this to $ret $ret[] = $arr[$i]; } // Return the array return $ret; } /** * If $pos is a number (integer or round()'able number), * we'll go ahead and make sure the position is there. * If so, we'll return it. */ if (is_int($pos) || is_numeric($pos)) { // This is just in case it was given screwy or as a non-integer if (!is_int($pos)) $pos = (int)round($pos); // If we want to start the array count at 1, do that now if (isset($shift) ($shift === true || $shift === 1)) { // but only if the number isn't zero if ($pos !== 0) --$pos; } // Return the single position if it exists if (isset($arr[$pos]) !empty($arr[$pos])) return $arr[$pos]; } /** * If we've failed every case, something is either * wrong or we supplied bad data. Return false. * Either way, feel free to add some trigger_error() * stuff here if you want to have the function hold * your hand. */ return false; } /** * Some simple examples */ $foo = 'apple,banana,carrot,orange,carrot,lettuce,tomato,beer,carrot,idiot'; return_item($foo,',',7); // Returns 'beer' return_item($foo,'carrot',0); // Returns 'apple,banana,' return_item($foo,','); // Returns all items in an array return_item($foo,',',array(0,'2',6.6)); // Returns array: apple,carrot,beer return_item($foo,',',1,true); // Returns 'apple' ? Of course, as with almost all code I submit here, it's typed directly into this window and is untested, so you use it at your own risk, your mileage may vary, see a doctor if you have an erection lasting more than four hours, et cetera. Happy Friday, all. -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array question
Tanks for all of your responses! I guess a function is the way to go. I just have to see if the situation comes up enough times to justify the function approach. @Dan: I really enjoyed your disclaimer :D -- Sorin Buturugeanu www.soin.ro http://www.facebook.com/buturugeanu http://www.twitter.com/soinrohttp://www.soin.ro/feed/blogblog: Despre Launch48 si ce poti face in 2 zile http://www.soin.ro/b75 On 17 December 2010 23:48, Daniel Brown danbr...@php.net wrote: On Fri, Dec 17, 2010 at 15:52, Sorin Buturugeanu m...@soin.ro wrote: Hello all! I have a question regarding arrays and the way I can use a value. Let's say I have this string: $s = 'banana,apple,mellon,grape,nut,orange' I want to explode it, and get the third value. For this I would normally do: $a = explode(',', $s); echo $s[2]; That's all fine, but is there a way to get the value directly, without having to write another line in my script. I mean something like this: echo explode(',', $s)[2]; or echo {explode(',', $s)}[2]; I couldn't find out this answer anywhere, that's why I posted here. Unfortunately, no --- at least, not yet. Chaining discussions come up now and again, so it's quite possible that future versions of PHP will have something similar. That said, for now you could do something like this: ?php /** * mixed return_item( string $car, mixed $pos ) * - $str The original string * - $charThe delimiting character(s) by which to explode * - $pos The position to return * - $shift Whether or not we should see 1 as the first array position */ function return_item($str,$char,$pos=null,$shift=false) { // Make sure $char exists in $str, return false if not. if (!strpos($str,$char)) return false; // Split $char by $str into the array $arr $arr = explode($char,$str); // If $pos undefined or null, return the whole array if (is_null($pos)) return $arr; // If $pos is an array, return the requested positions if (isset($pos) is_array($pos) !empty($pos)) { // Instantiate a second array container for return $ret = array(); // Iterate foreach ($pos as $i) { // This is just in case it was given screwy or a number as a non-integer if (!is_int($i) is_numeric($i)) $i = (int)round($i); // Make sure $i is now an integer and that position exists if (!is_int($i) || !isset($arr[$i]) || empty($arr[$i])) continue; // If all seems okay, append this to $ret $ret[] = $arr[$i]; } // Return the array return $ret; } /** * If $pos is a number (integer or round()'able number), * we'll go ahead and make sure the position is there. * If so, we'll return it. */ if (is_int($pos) || is_numeric($pos)) { // This is just in case it was given screwy or as a non-integer if (!is_int($pos)) $pos = (int)round($pos); // If we want to start the array count at 1, do that now if (isset($shift) ($shift === true || $shift === 1)) { // but only if the number isn't zero if ($pos !== 0) --$pos; } // Return the single position if it exists if (isset($arr[$pos]) !empty($arr[$pos])) return $arr[$pos]; } /** * If we've failed every case, something is either * wrong or we supplied bad data. Return false. * Either way, feel free to add some trigger_error() * stuff here if you want to have the function hold * your hand. */ return false; } /** * Some simple examples */ $foo = 'apple,banana,carrot,orange,carrot,lettuce,tomato,beer,carrot,idiot'; return_item($foo,',',7); // Returns 'beer' return_item($foo,'carrot',0); // Returns 'apple,banana,' return_item($foo,','); // Returns all items in an array return_item($foo,',',array(0,'2',6.6)); // Returns array: apple,carrot,beer return_item($foo,',',1,true); // Returns 'apple' ? Of course, as with almost all code I submit here, it's typed directly into this window and is untested, so you use it at your own risk, your mileage may vary, see a doctor if you have an erection lasting more than four hours, et cetera. Happy Friday, all. -- /Daniel P. Brown Network Infrastructure Manager Documentation, Webmaster Teams http://www.php.net/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array problem
On 27 October 2010 22:15, Kevin Kinsey k...@daleco.biz wrote: Marc Guay wrote: As Nicholas pointed out, the extra underscore in the key is the issue. That's way too easy a fix. I think he should check to make sure his version of PHP was compiled with the right extensions and that the browser isn't doing something unpredictably bizarre when submitting the form. Just checked the card file, today's cause is: Sunspots. KDK I always believed that cosmic radiation was the cause. -- Richard Quadling Twitter : EE : Zend @RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array problem
From: Richard Quadling On 27 October 2010 22:15, Kevin Kinsey k...@daleco.biz wrote: Marc Guay wrote: As Nicholas pointed out, the extra underscore in the key is the issue. That's way too easy a fix. I think he should check to make sure his version of PHP was compiled with the right extensions and that the browser isn't doing something unpredictably bizarre when submitting the form. Just checked the card file, today's cause is: Sunspots. I always believed that cosmic radiation was the cause. I'll second the cosmic radiation. We are currently in the low activity portion of the 11 year sunspot cycle[1], and predictions of the next high are lower than most cycles recorded over the past century[2]. So that one is not an easy sell right now. Bob McConnell [1] http://www.windows2universe.org/sun/activity/sunspot_cycle.html [2] http://solarscience.msfc.nasa.gov/predict.shtml -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array problem
Marc Guay wrote: As Nicholas pointed out, the extra underscore in the key is the issue. That's way too easy a fix. I think he should check to make sure his version of PHP was compiled with the right extensions and that the browser isn't doing something unpredictably bizarre when submitting the form. Just checked the card file, today's cause is: Sunspots. KDK -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array / form processing
Ron Piggott schrieb: I am writing a custom shopping cart that eventually the cart will be uploaded to PayPal for payment. I need to be able to include the option that the purchase is a gift certificate. At present my add to cart function goes like this: === # Gift Certificate: 1 is a gift; 2 is personal use if ( $gift_certificate == yes ) { $gift = 1; } else { $gift = 2; } $_SESSION['life_coaching_order'][$product][$gift]['quantity'] = $_SESSION['life_coaching_order'][$product][$gift]['quantity'] + 1; === Now I need to display the shopping cart contents. I want to do this through an array as the contents of the shopping cart are in a session variable. I start displaying the shopping cart contents by a FOREACH loop: === foreach ($_SESSION['life_coaching_order'] AS $coaching_fee_theme_reference = $value ) { === What I need help with is that I don't know how to test the value of $gift in the above array if it is a 1 or 2 (which symbolizes this is a gift certificate). I have something like this in mind: if ( $_SESSION['life_coaching_order'] == 2 ) { But I don't know how to access all the components of the array while I am going through the FOREACH loop. By using a 1 or 2 I have made gift certificates their own product. If you a better method I could use please provide me with this feedback. Ron The Verse of the Day Encouragement from God's Word www.TheVerseOfTheDay.info First at all, I wouldn't use 1 or 2 for defining important informations. use something like define('ORDER_GIFT', 1); define('ORDER_PERSONAL',2); If you want to check all values of your array you can use several foreach loops like foreach ($_SESSION['life_coaching_order'] AS $coaching_product = $tmp_array) { foreach ($tmp_array as $coaching_gift = $tmp_array2) { switch ($coaching_gift) case ORDER_GIFT: break; case ORDER_PERSONAL: break; ) } } Personally I would prefer writing a class like class Order { private $product; private $gift; private $quantity; const ORDER_GIFT=1; const ORDER_PERSONAL=2; function getGift() { return $this - gift; } } using $_SESSION['life_coaching_order'][] = new Order(); foreach ( $_SESSION['life_coaching_order'] as $order ) { switch ( $order - getGift() ) case ORDER_GIFT: break; case ORDER_PERSONAL: break; } I hope that will help you, Sebastian http://elygor.de -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array / form processing
$_SESSION['life_coaching_order'][$product][$gift]['quantity'] = $_SESSION['life_coaching_order'][$product][$gift]['quantity'] + 1; === ... === foreach ($_SESSION['life_coaching_order'] AS $coaching_fee_theme_reference = $value ) { === In this example $value would be an array. To test if it is a gift or not you would do this from within the foreach loop: //gift if ( isset($value[1]) isset($value[1]['quantity']) ) { $gift_quantity = $value[1]['quantity']; } //personal use if ( isset($value[2]) isset($value[2]['quantity']) ) { $personal_quantity = $value[2]['quantity']; } Technically the above IF's are optional, but they are proper syntax. I don't know how you are with OOP, but you may have more luck using objects instead of a complex array. Chris H. On Thu, Oct 7, 2010 at 3:35 PM, Ron Piggott ron.pigg...@actsministries.orgwrote: I am writing a custom shopping cart that eventually the cart will be uploaded to PayPal for payment. I need to be able to include the option that the purchase is a gift certificate. At present my add to cart function goes like this: === # Gift Certificate: 1 is a gift; 2 is personal use if ( $gift_certificate == yes ) { $gift = 1; } else { $gift = 2; } $_SESSION['life_coaching_order'][$product][$gift]['quantity'] = $_SESSION['life_coaching_order'][$product][$gift]['quantity'] + 1; === Now I need to display the shopping cart contents. I want to do this through an array as the contents of the shopping cart are in a session variable. I start displaying the shopping cart contents by a FOREACH loop: === foreach ($_SESSION['life_coaching_order'] AS $coaching_fee_theme_reference = $value ) { === What I need help with is that I don't know how to test the value of $gift in the above array if it is a 1 or 2 (which symbolizes this is a gift certificate). I have something like this in mind: if ( $_SESSION['life_coaching_order'] == 2 ) { But I don't know how to access all the components of the array while I am going through the FOREACH loop. By using a 1 or 2 I have made gift certificates their own product. If you a better method I could use please provide me with this feedback. Ron The Verse of the Day Encouragement from God's Word www.TheVerseOfTheDay.info -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array / form processing
Many thanks, Chris. I have one additional question about this shopping cart project. I need to make a submit button for the purpose of removing an item from the shopping cart. input type=submit name=submit value=Remove class=place_order/ What I am struggling with is to find an effective method for passing the product serial number (auto_increment in the table it is stored in) so I know which product the user is removing from their purchase. Then I will just unset the session variable that matches. What are your suggestion(s)? Thank you your help with my original question Chris. Ron $_SESSION['life_coaching_order'][$product][$gift]['quantity'] = $_SESSION['life_coaching_order'][$product][$gift]['quantity'] + 1; === ... === foreach ($_SESSION['life_coaching_order'] AS $coaching_fee_theme_reference = $value ) { === In this example $value would be an array. To test if it is a gift or not you would do this from within the foreach loop: //gift if ( isset($value[1]) isset($value[1]['quantity']) ) { $gift_quantity = $value[1]['quantity']; } //personal use if ( isset($value[2]) isset($value[2]['quantity']) ) { $personal_quantity = $value[2]['quantity']; } Technically the above IF's are optional, but they are proper syntax. I don't know how you are with OOP, but you may have more luck using objects instead of a complex array. Chris H. On Thu, Oct 7, 2010 at 3:35 PM, Ron Piggott ron.pigg...@actsministries.orgwrote: I am writing a custom shopping cart that eventually the cart will be uploaded to PayPal for payment. I need to be able to include the option that the purchase is a gift certificate. At present my add to cart function goes like this: === # Gift Certificate: 1 is a gift; 2 is personal use if ( $gift_certificate == yes ) { $gift = 1; } else { $gift = 2; } $_SESSION['life_coaching_order'][$product][$gift]['quantity'] = $_SESSION['life_coaching_order'][$product][$gift]['quantity'] + 1; === Now I need to display the shopping cart contents. I want to do this through an array as the contents of the shopping cart are in a session variable. I start displaying the shopping cart contents by a FOREACH loop: === foreach ($_SESSION['life_coaching_order'] AS $coaching_fee_theme_reference = $value ) { === What I need help with is that I don't know how to test the value of $gift in the above array if it is a 1 or 2 (which symbolizes this is a gift certificate). I have something like this in mind: if ( $_SESSION['life_coaching_order'] == 2 ) { But I don't know how to access all the components of the array while I am going through the FOREACH loop. By using a 1 or 2 I have made gift certificates their own product. If you a better method I could use please provide me with this feedback. Ron The Verse of the Day Encouragement from God's Word www.TheVerseOfTheDay.info -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php The Verse of the Day Encouragement from God's Word www.TheVerseOfTheDay.info -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array / form processing
input type=submit name=submit value=Remove class=place_order/ I don't know what the context is like, but you may be better off just using an entire form here with hidden fields. i.e. form target=... action=... input type=hidden name=submit value=Remove / input type=hidden name=product_so value=1234 / input type=submit value=Remove class=place_order/ /form Without knowing what else is going on in your page, and how the request is being handled on the server, it's kind of hard to give exact advice. :) Chris H.
Re: [PHP] Array question
I'd also like to add to that: $array = array(); $array[] = 'text'; $array[2] = 123; $array[] = 'hello'; Would output: $array( 0 = 'text', 2 = 123, 3 = 'hello', ); Note the missing index 1, as php makes a numerical index that is one greater than the highest already in use. As the index 2 was explicitly created, php made the next one at 3. Thanks, Ash http://www.ashleysheridan.co.uk - Reply message - From: chris h chris...@gmail.com Date: Sat, Sep 25, 2010 22:05 Subject: [PHP] Array question To: MikeB mpbr...@gmail.com Cc: php-general@lists.php.net Mike, $results[] will automatically push a value unto the end of an array. So doing this... -- $magic = array(); $magic[] = 'a'; $magic[] = 'b'; $magic[] = 'c'; - is exactly this same as doing this... -- $normal = array(); $normal[0] = 'a'; $normal[1] = 'b'; $normal[2] = 'c'; - And yes, in your example $results[] would be equivalent to $results[$j] For more reference: http://www.php.net/manual/en/language.types.array.php Chris H. On Sat, Sep 25, 2010 at 4:31 PM, MikeB mpbr...@gmail.com wrote: I have the following code: $query = SELECT * FROM classics; $result = mysql_query($query); if (!$result) die (Database access failed: . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j $rows ; ++$j) { $results[] = mysql_fetch_array($result); } mysql_close($db_server); My question, in the loop, why does tha author use: $results[] = mysql_fetch_array($result); instead of (as I would expect): $results[$j] = mysql_fetch_array($result);? What PHP magic is at work here? Thanks. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array question
At 3:31 PM -0500 9/25/10, MikeB wrote: -snip- My question, in the loop, why does tha author use: $results[] = mysql_fetch_array($result); instead of (as I would expect): $results[$j] = mysql_fetch_array($result);? What PHP magic is at work here? Mike: That's just a shorthand way to populate an array in PHP. One of the reasons for this feature is that somewhere in your code you may not know what the next index should be. So, if you use -- $results[] = $next_item; -- then the $next_item will be automagically added to the next available index in the array. So you may be right in calling it PHP magic because I have not seen this in other languages. Understand? Cheers, tedd -- --- http://sperling.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array question
Mike, $results[] will automatically push a value unto the end of an array. So doing this... -- $magic = array(); $magic[] = 'a'; $magic[] = 'b'; $magic[] = 'c'; - is exactly this same as doing this... -- $normal = array(); $normal[0] = 'a'; $normal[1] = 'b'; $normal[2] = 'c'; - And yes, in your example $results[] would be equivalent to $results[$j] For more reference: http://www.php.net/manual/en/language.types.array.php Chris H. On Sat, Sep 25, 2010 at 4:31 PM, MikeB mpbr...@gmail.com wrote: I have the following code: $query = SELECT * FROM classics; $result = mysql_query($query); if (!$result) die (Database access failed: . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j $rows ; ++$j) { $results[] = mysql_fetch_array($result); } mysql_close($db_server); My question, in the loop, why does tha author use: $results[] = mysql_fetch_array($result); instead of (as I would expect): $results[$j] = mysql_fetch_array($result);? What PHP magic is at work here? Thanks. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array help.
On Jul 30, 2010, at 2:36 PM, Paul Halliday wrote: I have a query that may not always return a result for a value, I need to reflect this with a 0. I am trying to overcome this by doing this (the keys are ID's): while ($row = mysql_fetch_row($statusQuery)) { $cat = array(0=0,1=0,11=0,12=0,13=0,14=0,15=0,16=0,17=0,19=0); switch ($row[1]) { case 0: $cat[0] = $row[0]; break; case 1: $cat[1] = $row[0]; break; case 11: $cat[11] = $row[0]; break; case 12: $cat[12] = $row[0]; break; case 13: $cat[13] = $row[0]; break; case 14: $cat[14] = $row[0]; break; case 15: $cat[15] = $row[0]; break; case 16: $cat[16] = $row[0]; break; case 17: $cat[17] = $row[0]; break; case 19: $cat[19] = $row[0]; break; } print_r($cat); } Which gives me this: Array ( [0] = 15547 [1] = 0 [11] = 0 [12] = 0 [13] = 0 [14] = 0 [15] = 0 [16] = 0 [17] = 0 [19] = 0 ) Array ( [0] = 0 [1] = 0 [11] = 0 [12] = 0 [13] = 0 [14] = 0 [15]s = 30 [16] = 0 [17] = 0 [19] = 0 ) The query only return 2 rows: 15 | 30 0 | 15547 What am I doing wrong? Is there a more elegant way to achieve what I want? Thanks. -- Paul Halliday Ideation | Individualization | Learner | Achiever | Analytical http://www.pintumbler.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Paul- Why not say: $cat = array(); if(isset($row[1]) { $cat[$row[1]] = $row[0]; } print_r($cat); Regards, -Josh -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array help.
On Fri, Jul 30, 2010 at 3:44 PM, Joshua Kehn josh.k...@gmail.com wrote: On Jul 30, 2010, at 2:36 PM, Paul Halliday wrote: I have a query that may not always return a result for a value, I need to reflect this with a 0. I am trying to overcome this by doing this (the keys are ID's): while ($row = mysql_fetch_row($statusQuery)) { $cat = array(0=0,1=0,11=0,12=0,13=0,14=0,15=0,16=0,17=0,19=0); switch ($row[1]) { case 0: $cat[0] = $row[0]; break; case 1: $cat[1] = $row[0]; break; case 11: $cat[11] = $row[0]; break; case 12: $cat[12] = $row[0]; break; case 13: $cat[13] = $row[0]; break; case 14: $cat[14] = $row[0]; break; case 15: $cat[15] = $row[0]; break; case 16: $cat[16] = $row[0]; break; case 17: $cat[17] = $row[0]; break; case 19: $cat[19] = $row[0]; break; } print_r($cat); } Which gives me this: Array ( [0] = 15547 [1] = 0 [11] = 0 [12] = 0 [13] = 0 [14] = 0 [15] = 0 [16] = 0 [17] = 0 [19] = 0 ) Array ( [0] = 0 [1] = 0 [11] = 0 [12] = 0 [13] = 0 [14] = 0 [15]s = 30 [16] = 0 [17] = 0 [19] = 0 ) The query only return 2 rows: 15 | 30 0 | 15547 What am I doing wrong? Is there a more elegant way to achieve what I want? Thanks. -- Paul Halliday Ideation | Individualization | Learner | Achiever | Analytical http://www.pintumbler.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Paul- Why not say: $cat = array(); if(isset($row[1]) { $cat[$row[1]] = $row[0]; } print_r($cat); Regards, -Josh I need the results that don't have values assigned though. ex: c = 0 h = 9 t = 0 f = 21 Even if the query returned only: h = 9 f = 21 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array help.
On Jul 30, 2010, at 3:03 PM, Paul Halliday wrote: Paul- Why are those values not defaulted to 0 in the database? Regards, -Josh They are defaulted, the query is grouping: select count(status) as count, status from table group by status order by status desc; Paul- Correct, so stuff with a status of 0 will still show up unless I'm missing something. Regards, -Josh -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: php array in different OS
'Twas brillig, and fyang at 22/07/10 03:34 did gyre and gimble: Dear Bob McConnell, Thank you for your reply. I really post the same message eight times because of the first e-mail authentication.please remove the extra e-mail in your free time. There are two servers ,the first installation of 32-bit linux(RHEL),the second installlation 64-bit linux(CENTOS). PHP version on 32-bit linux(RHEL):5.2.7 PHP version on 64-bit linux(CENTOS):5.2.13 I found this problem,because the software transplantation.In the 64-bit systems,the array seems to always have limited capacity. I'm not sure that is php version problem or need other configurations. I suspect it's just different configuration. That said, I've generally found that 64bit versions of PHP need more memory than their 32bit equivs, so perhaps all you need to do is something like: ini_set('memory_limit', '50M'); and you'll be fine. Col -- Colin Guthrie gmane(at)colin.guthr.ie http://colin.guthr.ie/ Day Job: Tribalogic Limited [http://www.tribalogic.net/] Open Source: Mandriva Linux Contributor [http://www.mandriva.com/] PulseAudio Hacker [http://www.pulseaudio.org/] Trac Hacker [http://trac.edgewall.org/] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: php array in different OS
Dear Colin Guthrie , Thanks for your help very much. According to your suggestion, I have solved the question. best wish, Yang Fei 2010-7-24
RE: [PHP] Array form processing
-Original Message- From: Ron Piggott [mailto:ron.pigg...@actsministries.org] Sent: 29 June 2010 22:22 Am I on the right track? I don't know what to do with the second FOREACH Sort of. ?php foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; if ( $val == Array ) { I would prefer to use is_array() here: if (is_array($val)) $i=0; At this point, you've just proved that $val is an array (whichever test you use!), so simply foreach it like one. I know you know how to do that as you did it with $_REQUEST above! foreach ($val) { echo $val[$i]br; $i++; } foreach ($val as $option) { echo $optionbr /\n; } } } ? Cheers! Mike -- Mike Ford, Electronic Information Developer, Libraries and Learning Innovation, Leeds Metropolitan University, C507, Civic Quarter Campus, Woodhouse Lane, LEEDS, LS1 3HE, United Kingdom Email: m.f...@leedsmet.ac.uk Tel: +44 113 812 4730 To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array form processing
At 4:54 PM -0400 6/29/10, Ron Piggott wrote: I am trying to process a form where the user uses checkboxes: input type=checkbox name=painDesc[] value=1 /Sharp input type=checkbox name=painDesc[] value=2 /Stabbing input type=checkbox name=painDesc[] value=3 /Jabbing When I do: foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; } The output is: painDesc: Array I need to know the values of the array (IE to know what the user is checking), not that there is an array. I hope to save these values to the database. Thank you. Ron Ron: Try this: http://php1.net/b/form-checkbox/ If you want the form to retain the values, try this: http://php1.net/b/form-checkbox1/ Cheers, tedd -- --- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array form processing
On Tue, 2010-06-29 at 16:54 -0400, Ron Piggott wrote: I am trying to process a form where the user uses checkboxes: input type=checkbox name=painDesc[] value=1 /Sharp input type=checkbox name=painDesc[] value=2 /Stabbing input type=checkbox name=painDesc[] value=3 /Jabbing When I do: foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; } The output is: painDesc: Array I need to know the values of the array (IE to know what the user is checking), not that there is an array. I hope to save these values to the database. Thank you. Ron You need to iterate that array, as that holds the values of everything sent by the browser Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Array form processing
The painDesc array is what that should be iterated. --Shreyas On Wed, Jun 30, 2010 at 2:27 AM, Ashley Sheridan a...@ashleysheridan.co.ukwrote: On Tue, 2010-06-29 at 16:54 -0400, Ron Piggott wrote: I am trying to process a form where the user uses checkboxes: input type=checkbox name=painDesc[] value=1 /Sharp input type=checkbox name=painDesc[] value=2 /Stabbing input type=checkbox name=painDesc[] value=3 /Jabbing When I do: foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; } The output is: painDesc: Array I need to know the values of the array (IE to know what the user is checking), not that there is an array. I hope to save these values to the database. Thank you. Ron You need to iterate that array, as that holds the values of everything sent by the browser Thanks, Ash http://www.ashleysheridan.co.uk -- Regards, Shreyas Agasthya
Re: [PHP] Array form processing
Am I on the right track? I don't know what to do with the second FOREACH ?php foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; if ( $val == Array ) { $i=0; foreach ($val) { echo $val[$i]br; $i++; } } } ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array form processing
Ron Piggott wrote: I am trying to process a form where the user uses checkboxes: input type=checkbox name=painDesc[] value=1 /Sharp input type=checkbox name=painDesc[] value=2 /Stabbing input type=checkbox name=painDesc[] value=3 /Jabbing When I do: foreach($_REQUEST as $key = $val) { $$key = $val; echo $key . : . $val . br; } The output is: painDesc: Array I need to know the values of the array (IE to know what the user is checking), not that there is an array. I hope to save these values to the database. Thank you. Ron Think about it... You would not ?php echo $_REQUEST; ? and expect to get the value of any form field would you. No, you wouldn't. Given the following form... form Titleinput type=text name=title value= /br / Subjectinput type=text name=subject value= /br / input type=submit name=submit value=Send it! / /form on the processing page, I would access those variables by writing the following. echo $_REQUEST['title']; echo $_REQUEST['subject']; With that said, going back to your issue, you would do this: if ( $_REQUEST['painDesc'] count($_REQUEST['painDesc']) ) { foreach($_REQUEST['painDesc'] as $key = $val) { echo {$key}:{$val}br /; } } -- Jim Lucas A: Maybe because some people are too annoyed by top-posting. Q: Why do I not get an answer to my question(s)? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, Jun 08, 2010 at 04:12:42PM +0300, Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; If the index for (integer) 3, the first example is correct. If the index is (string) '3', the second example is correct. $i = 7; $array[$i] = ''; or $array[$i] = ''; There's no reason to use $i. The end result will be the same, but in the case of $i, you're forcing the PHP interpreter to interpret the string $i, looking for variables (like $i), and output whatever else is in the string (which in this case is nothing). Also, if $i is an integer, you have the same problem as above. In the first case, you get $array[7]. In the second case, you get $array['7']. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, 2010-06-08 at 16:12 +0300, Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Br Tanel The two indexes are equivalent, although I reckon the integer one will give better performance over the string. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array key's: which is correct?
Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Cheers, Rob. -- E-Mail Disclaimer: Information contained in this message and any attached documents is considered confidential and legally protected. This message is intended solely for the addressee(s). Disclosure, copying, and distribution are prohibited unless authorized. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, 2010-06-08 at 09:38 -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Cheers, Rob. -- E-Mail Disclaimer: Information contained in this message and any attached documents is considered confidential and legally protected. This message is intended solely for the addressee(s). Disclosure, copying, and distribution are prohibited unless authorized. Yeah, I found that out the hard way when I was trying to make an array of Gantt tasks, and realised that all my nice task numbers were changed! Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array key's: which is correct?
On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array key's: which is correct?
On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Regards Peter -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind BeWelcome/Couchsurfing: Fake51 Twitter: http://twitter.com/kafe15 /hype -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote: On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Regards Peter They are. Go look at Robs earlier example. Even building upon that to make a float value where it doesn't equate to an integer, it is still cast as an integer unless it's inside a string: $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, 6.5= 6.5, ); var_dump( array_keys( $array ) ); That's Robs code, but I added in the last element to show how a float index is converted to an integer. Putting the float value inside a string solves the issue. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array key's: which is correct?
On 8 June 2010 16:53, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote: On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Regards Peter They are. Go look at Robs earlier example. Even building upon that to make a float value where it doesn't equate to an integer, it is still cast as an integer unless it's inside a string: $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, 6.5 = 6.5, ); var_dump( array_keys( $array ) ); That's Robs code, but I added in the last element to show how a float index is converted to an integer. Putting the float value inside a string solves the issue. Did you read what I wrote? ***Floats in quotes*** are not cast to int when used as array keys. Just an FYI :) I tested Robs example, that's how I know that floats in quotes are not converted to ints, whether or not you use '4.0' or '6.5' Regards Peter -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind BeWelcome/Couchsurfing: Fake51 Twitter: http://twitter.com/kafe15 /hype -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
On Tue, 2010-06-08 at 17:11 +0200, Peter Lind wrote: On 8 June 2010 16:53, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 16:44 +0200, Peter Lind wrote: On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Regards Peter They are. Go look at Robs earlier example. Even building upon that to make a float value where it doesn't equate to an integer, it is still cast as an integer unless it's inside a string: $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, 6.5 = 6.5, ); var_dump( array_keys( $array ) ); That's Robs code, but I added in the last element to show how a float index is converted to an integer. Putting the float value inside a string solves the issue. Did you read what I wrote? ***Floats in quotes*** are not cast to int when used as array keys. Just an FYI :) I tested Robs example, that's how I know that floats in quotes are not converted to ints, whether or not you use '4.0' or '6.5' Regards Peter -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind BeWelcome/Couchsurfing: Fake51 Twitter: http://twitter.com/kafe15 /hype Sorry, my bad, I misread your email, you were right! Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] array key's: which is correct?
On Tue, Jun 08, 2010 at 04:44:53PM +0200, Peter Lind wrote: On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Umm, yes, you are correct. I pasted Rob's code into a test file, added some other print_r()s and such, just to look at the whole issue. I'm *still* examining the results, trying to wrap my wits around why things are done this way. Paul -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] array key's: which is correct?
Paul M Foster wrote: On Tue, Jun 08, 2010 at 04:44:53PM +0200, Peter Lind wrote: On 8 June 2010 16:38, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote: On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote: Tanel Tammik wrote: Hi, which one is correct or better? $array[3] = ''; or $array['3'] = ''; $i = 7; $array[$i] = ''; or $array[$i] = ''; Sometimes it is good to illustrate the correct answer: ?php $array = array ( '1' = '1', '2' = '2', 'three' = 'three', '4.0' = '4.0', 5.0 = 5.0, ); var_dump( array_keys( $array ) ); ? The answer is surprising (well, not really :) and certainly advocates against making literal strings of integers or manually converting a string integer to a real integer or using floating point keys. Curse you, Rob Cummings! ;-} I was stunned at the results of this. I assumed that integers cast as strings would remain strings as indexes. Not so. And then float indexes cast to ints. Argh! My advice to the original poster was slightly incorrect. But I would still encourage you to avoid enclosing variables in double-quotes unnecessarily. (And integers in single-quotes for that matter.) Paul -- Paul M. Foster The obvious way around this would be to include some sort of character in the index that can't be cast to an integer, so instead of $array[1.0] which would equate to $array[1] maybe add an underscore to make it $array['_1.0']. It's not the prettiest of solutions, but it does mean that indexes are kept as you intended, and you need only strip out the first character, although I imagine a lot of string manipulation on a large array would decrease performance. Floats in quotes are not cast to int when used as array keys. Just an FYI :) Umm, yes, you are correct. I pasted Rob's code into a test file, added some other print_r()s and such, just to look at the whole issue. I'm *still* examining the results, trying to wrap my wits around why things are done this way. If I were to hazard a guess as to the why of the current functionality, I would say converting an integer string to a real i nt is optimal with respect to both memory and processing when trying to find values by key. As for floating points... Due to the inability to accurately represent some floating point numbers in binary, one would often not get what one expects even when converting to a string. So maybe integer was chosen since it was more optimal than a string. Cheers, Rob. -- E-Mail Disclaimer: Information contained in this message and any attached documents is considered confidential and legally protected. This message is intended solely for the addressee(s). Disclosure, copying, and distribution are prohibited unless authorized. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52ARMENIA 215 CANADA 57CANADA 261 COLOMBIA 53EGYPT 62INDIA 50INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52 ARMENIA 215 CANADA 57 CANADA 261 COLOMBIA 53 EGYPT 62 INDIA 50 INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare I was actually hoping to have them arranged like: $col1[0] = INDIA $col2[0] = 112 $col1[1] = CANADA $col2[1] = 272 ... Thanks. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
Paul Halliday wrote: On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52ARMENIA 215 CANADA 57CANADA 261 COLOMBIA 53EGYPT 62INDIA 50INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare I was actually hoping to have them arranged like: $col1[0] = INDIA $col2[0] = 112 $col1[1] = CANADA $col2[1] = 272 ... Thanks. Well, then take what I gave you and do this: $group[lookup($row[1])][] = $row[0]; foreach ( $group AS $x = $y ) { $col1[] = $x; $col2[] = array_sum($y); } In the end you will end up with this plaintext?php $data = array( array(52, 'ARMENIA'), array(215, 'CANADA'), array(57, 'CANADA'), array(261, 'COLOMBIA'), array(53, 'EGYPT'), array(62, 'INDIA'), array(50, 'INDIA'), ); foreach ( $data AS $row ) { $group[$row[1]][] = $row[0]; } print_r($group); foreach ( $group AS $x = $y ) { $col1[] = $x; $col2[] = array_sum($y); } print_r($col1); print_r($col2); -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52 ARMENIA 215 CANADA 57 CANADA 261 COLOMBIA 53 EGYPT 62 INDIA 50 INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare I was actually hoping to have them arranged like: $col1[0] = INDIA $col2[0] = 112 $col1[1] = CANADA $col2[1] = 272 ... Thanks. Well, then take what I gave you and do this: $group[lookup($row[1])][] = $row[0]; foreach ( $group AS $x = $y ) { $col1[] = $x; $col2[] = array_sum($y); } In the end you will end up with this plaintext?php $data = array( array(52, 'ARMENIA'), array(215, 'CANADA'), array(57, 'CANADA'), array(261, 'COLOMBIA'), array(53, 'EGYPT'), array(62, 'INDIA'), array(50, 'INDIA'), ); foreach ( $data AS $row ) { $group[$row[1]][] = $row[0]; } print_r($group); foreach ( $group AS $x = $y ) { $col1[] = $x; $col2[] = array_sum($y); } print_r($col1); print_r($col2); Perfect! and a lot simpler than I thought. Thanks. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
On 05/11/2010 02:17 PM, Paul Halliday wrote: On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52ARMENIA 215 CANADA 57CANADA 261 COLOMBIA 53EGYPT 62INDIA 50INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare I was actually hoping to have them arranged like: $col1[0] = INDIA $col2[0] = 112 $col1[1] = CANADA $col2[1] = 272 ... Thanks. I would probably do this: $col1 = $col2 = array(); while ($row = mysql_fetch_array($theData[0])) { $country = lookup($row[1]); if(($found = array_search($country, $col1)) !== false) { $col2[$found] += $row[0]; } else { $col1[] = $country; $col2[] = $row[0]; } } -- Thanks! -Shawn http://www.spidean.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array group and sum values.
On 05/11/2010 04:09 PM, Shawn McKenzie wrote: On 05/11/2010 02:17 PM, Paul Halliday wrote: On Tue, May 11, 2010 at 4:03 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: On Tue, May 11, 2010 at 2:25 PM, Jim Lucas li...@cmsws.com wrote: Paul Halliday wrote: I have this: while ($row = mysql_fetch_array($theData[0])) { $col1[] = $row[0]; $col2[] = lookup($row[1]); // this goes off and gets the country name. I then loop through col1 and col2 to produce something like this: 52ARMENIA 215 CANADA 57CANADA 261 COLOMBIA 53EGYPT 62INDIA 50INDIA Is there a way I can group these? Thanks! Group them?? How about this while ($row = mysql_fetch_array($theData[0])) { $col1[lookup($row[1])][] = $row[0]; which, using the data you showed, will give you this Array ( [ARMENIA] = Array ( [0] = 52 ) [CANADA] = Array ( [0] = 215 [1] = 57 ) [COLOMBIA] = Array ( [0] = 261 ) [EGYPT] = Array ( [0] = 53 ) [INDIA] = Array ( [0] = 62 [1] = 50 ) ) -- Jim Lucas Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them. Twelfth Night, Act II, Scene V by William Shakespeare I was actually hoping to have them arranged like: $col1[0] = INDIA $col2[0] = 112 $col1[1] = CANADA $col2[1] = 272 ... Thanks. I would probably do this: $col1 = $col2 = array(); while ($row = mysql_fetch_array($theData[0])) { $country = lookup($row[1]); if(($found = array_search($country, $col1)) !== false) { $col2[$found] += $row[0]; } else { $col1[] = $country; $col2[] = $row[0]; } } Although I myself would prefer it to be in this format: $result = array(); foreach($rows as $row) { $country = lookup($row[1]); if(isset($result[$country])) { $result[$country] += $row[0]; } else { $result[$country] = $row[0]; } } Which would give: array ( INDIA = 112 CANADA = 272 //etc... ) Then to use, just: foreach($result as $country = $value) { echo $country . ' ' . $value; // or whatever } -- Thanks! -Shawn http://www.spidean.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array to csv or excel in php
On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis vlachakis.mano...@gmail.com wrote: hallo there everyone.. i got an array from my database Help with Code Tagshttp://www.daniweb.com/forums/misc-explaincode.html?TB_iframe=trueheight=400width=680 *PHP Syntax* (Toggle Plain Texthttp://www.daniweb.com/forums/post1194347.html# ) 1. $save=split([|;],$listOfItems); and what i want i s after making some changes to the attributes on the array above to export them on an csv or excel format but directly as a message to the browser .. i dont want it to be saved on the server ... what i cant understand from the examples i found on the net .. is how to handle the files and which are created cause i just have the array in a php file nothing more... another thing i have in mind is to export from the ldap server the files directly but seems to me as the wrong way to do it thanks Often when outputting csv, I usually do something like this: ?php $fp = fopen('php://output', 'w') or die('Could not open stream'); foreach ($data as $row) { // Assumes that $row will be an array. // Manipulate the data in $row if necessary. fputcsv($fp, $row); } ? So far, it has worked pretty well and is much faster than any other way I have found to output the CSV data by iterating through the arrays manually. Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array to csv or excel in php
On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis vlachakis.mano...@gmail.com wrote: hallo there everyone.. i got an array from my database Help with Code Tagshttp://www.daniweb.com/forums/misc-explaincode.html?TB_iframe=trueheight=400width=680 *PHP Syntax* (Toggle Plain Texthttp://www.daniweb.com/forums/post1194347.html# ) 1. $save=split([|;],$listOfItems); and what i want i s after making some changes to the attributes on the array above to export them on an csv or excel format but directly as a message to the browser .. i dont want it to be saved on the server ... what i cant understand from the examples i found on the net .. is how to handle the files and which are created cause i just have the array in a php file nothing more... another thing i have in mind is to export from the ldap server the files directly but seems to me as the wrong way to do it thanks Often when outputting csv, I usually do something like this: ?php $fp = fopen('php://output', 'w') or die('Could not open stream'); foreach ($data as $row) { // Assumes that $row will be an array. // Manipulate the data in $row if necessary. fputcsv($fp, $row); } ? An interesting idea. I'd do: echo implode(',', $row); regards Peter -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind Flickr: http://www.flickr.com/photos/fake51 BeWelcome: Fake51 Couchsurfing: Fake51 /hype -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array to csv or excel in php
On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote: On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis 1. $save=split([|;],$listOfItems); and what i want i s after making some changes to the attributes on the array above to export them on an csv or excel format but directly as a message to the browser .. i dont want it to be saved on the server ... Often when outputting csv, I usually do something like this: ?php $fp = fopen('php://output', 'w') or die('Could not open stream'); foreach ($data as $row) { // Assumes that $row will be an array. // Manipulate the data in $row if necessary. fputcsv($fp, $row); } ? An interesting idea. I'd do: echo implode(',', $row); If it's very simple data that works, but it doesn't allow for the optional enclosure characters that fputcsv() uses in cases where a data element includes the column and/or row delimiter characters. I had originally written something using an array_map callback that did the optional enclosures as needed and then used echo implode() as you suggest, but found the solution I posted was shorter and faster. YMMV Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array to csv or excel in php
On 19 April 2010 17:40, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote: On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis 1. $save=split([|;],$listOfItems); and what i want i s after making some changes to the attributes on the array above to export them on an csv or excel format but directly as a message to the browser .. i dont want it to be saved on the server ... Often when outputting csv, I usually do something like this: ?php $fp = fopen('php://output', 'w') or die('Could not open stream'); foreach ($data as $row) { // Assumes that $row will be an array. // Manipulate the data in $row if necessary. fputcsv($fp, $row); } ? An interesting idea. I'd do: echo implode(',', $row); If it's very simple data that works, but it doesn't allow for the optional enclosure characters that fputcsv() uses in cases where a data element includes the column and/or row delimiter characters. I had originally written something using an array_map callback that did the optional enclosures as needed and then used echo implode() as you suggest, but found the solution I posted was shorter and faster. YMMV Andrew Yeah, was considering that point as well. I'd use the echo if the array values are getting modified anyway. Otherwise your solution is probably simpler. Regards Peter -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind Flickr: http://www.flickr.com/photos/fake51 BeWelcome: Fake51 Couchsurfing: Fake51 /hype -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array to csv or excel in php
For non-simple data I have been using PEAR's File_CSV package. It's proven itself very useful in regards to not having to determine in my own code whether something needs to be quoted etc etc - especially if the output CSV needs to be wholly RFC 4180 compliant. The documentation of it is rather minimal - at the moment you are dependant on the test/example files and the API docs but grokking how to use it is rather easy. k. On Mon, Apr 19, 2010 at 4:40 PM, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 11:14 AM, Peter Lind peter.e.l...@gmail.com wrote: On 19 April 2010 17:00, Andrew Ballard aball...@gmail.com wrote: On Mon, Apr 19, 2010 at 9:45 AM, Manolis Vlachakis 1. $save=split([|;],$listOfItems); and what i want i s after making some changes to the attributes on the array above to export them on an csv or excel format but directly as a message to the browser .. i dont want it to be saved on the server ... Often when outputting csv, I usually do something like this: ?php $fp = fopen('php://output', 'w') or die('Could not open stream'); foreach ($data as $row) { // Assumes that $row will be an array. // Manipulate the data in $row if necessary. fputcsv($fp, $row); } ? An interesting idea. I'd do: echo implode(',', $row); If it's very simple data that works, but it doesn't allow for the optional enclosure characters that fputcsv() uses in cases where a data element includes the column and/or row delimiter characters. I had originally written something using an array_map callback that did the optional enclosures as needed and then used echo implode() as you suggest, but found the solution I posted was shorter and faster. YMMV Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- http://blogs.linux.ie/kenguest/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array to csv or excel in php
[snip] to export them on an csv or excel format[/snip] Stupid browser tricks http://www.evolt.org/node/26896 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: I have the following scenario: $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $result = array_diff($array1, $array2); print_r($result); This returns: Array ( [1] = 34 [4] = 90 ) However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: 34 and 90 because they don't exist in $array2, AND 23 and 89 because they don't exist in $array1. So, is that a two step process of first doing an array_diff($array1, $array2) then reverse it by doing array_diff($array2, $array1) and merge/unique the results? Any caveats with that? $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); print_r($result); -- A I don't see any problems with doing it that way. This will only work as you intended if both arrays have the same number of elements I believe, otherwise you might end up with a situation where your final array has duplicates of the same number: $array1 = $array(1, 2, 3, 4, 5, 6); $array2 = $aray(1, 3, 2, 5); Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Array differences
Ashley Sheridan wrote: On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: I don't see any problems with doing it that way. By some freak chance I made an array diff class about 2 weeks ago which covers what you need. attached :) usage: $diff = new ArrayDiff( $old , $new ); $diff-l; // deleted items $diff-r; // inserted items $diff-u; // unchanged items The script is optimised for huge arrays, thus it's slower for small arrays than the usual array_diff but with large arrays it's quicker. Regards Nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
On Wed, Apr 14, 2010 at 12:03 PM, Nathan Rixham nrix...@gmail.com wrote: Ashley Sheridan wrote: On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: I don't see any problems with doing it that way. By some freak chance I made an array diff class about 2 weeks ago which covers what you need. attached :) usage: $diff = new ArrayDiff( $old , $new ); $diff-l; // deleted items $diff-r; // inserted items $diff-u; // unchanged items The script is optimised for huge arrays, thus it's slower for small arrays than the usual array_diff but with large arrays it's quicker. Regards Nathan -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php nice one :) i'll put it in a work-preperation folder for htmlMicroscope then, one of these days :) -- - Greetings from Rene7705, I have made some free open source webcomponents designed and written by me available through: http://code.google.com/u/rene7705/ , or http://mediabeez.ws (latest dev versions, currently offline) Personal info about me is available through http://www.facebook.com/rene7705 - -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
On 4/14/2010 2:39 AM, Ashley Sheridan wrote: On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); print_r($result); I don't see any problems with doing it that way. This will only work as you intended if both arrays have the same number of elements I believe, otherwise you might end up with a situation where your final array has duplicates of the same number: $array1 = $array(1, 2, 3, 4, 5, 6); $array2 = $aray(1, 3, 2, 5); Wouldn't array_unique() take care of that though? Your example above returns 4 and 6, which would be correct. A -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
Maybe this one works? array_diff(array_unique($array1 + $array2), array_intersect($array1, $array2)) On Wed, Apr 14, 2010 at 4:39 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: I have the following scenario: $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $result = array_diff($array1, $array2); print_r($result); This returns: Array ( [1] = 34 [4] = 90 ) However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: 34 and 90 because they don't exist in $array2, AND 23 and 89 because they don't exist in $array1. So, is that a two step process of first doing an array_diff($array1, $array2) then reverse it by doing array_diff($array2, $array1) and merge/unique the results? Any caveats with that? $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); print_r($result); -- A I don't see any problems with doing it that way. This will only work as you intended if both arrays have the same number of elements I believe, otherwise you might end up with a situation where your final array has duplicates of the same number: $array1 = $array(1, 2, 3, 4, 5, 6); $array2 = $aray(1, 3, 2, 5); Thanks, Ash http://www.ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array differences
No because that only does a one-way comparison. It only tells me what's missing from $array2. I need it from both arrays. That's why I'm comparing 1 versus 2, then 2 versus 1, and then doing a merge/unique on the result. $array1 = array(1, 2, 3, 4, 5, 6); $array2 = array(1, 3, 2, 8, 9); $result = array_diff(array_unique($array1 + $array2), array_intersect($array1, $array2)); = (4, 5, 6) Versus: $array1 = array(1, 2, 3, 4, 5, 6); $array2 = array(1, 3, 2, 8, 9); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); = (4, 5, 6, 8, 9) This second $result is what I want. So far I haven't noticed any problems doing it this way ... yet. I'm sure someone will tell me otherwise. Ash -Original Message- From: Ryan Sun [mailto:ryansu...@gmail.com] Sent: Wednesday, April 14, 2010 8:45 AM To: a...@ashleysheridan.co.uk Cc: Ashley M. Kirchner; php-general@lists.php.net Subject: Re: [PHP] Array differences Maybe this one works? array_diff(array_unique($array1 + $array2), array_intersect($array1, $array2)) On Wed, Apr 14, 2010 at 4:39 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Tue, 2010-04-13 at 23:01 -0600, Ashley M. Kirchner wrote: I have the following scenario: $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $result = array_diff($array1, $array2); print_r($result); This returns: Array ( [1] = 34 [4] = 90 ) However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: 34 and 90 because they don't exist in $array2, AND 23 and 89 because they don't exist in $array1. So, is that a two step process of first doing an array_diff($array1, $array2) then reverse it by doing array_diff($array2, $array1) and merge/unique the results? Any caveats with that? $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); print_r($result); -- A I don't see any problems with doing it that way. This will only work as you intended if both arrays have the same number of elements I believe, otherwise you might end up with a situation where your final array has duplicates of the same number: $array1 = $array(1, 2, 3, 4, 5, 6); $array2 = $aray(1, 3, 2, 5); Thanks, Ash http://www.ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
Ashley M. Kirchner wrote: $array1 = array(1, 2, 3, 4, 5, 6); $array2 = array(1, 3, 2, 8, 9); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); = (4, 5, 6, 8, 9) Hi Ash, Isn't the array_unique() unnecessary? Mike -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array differences
-Original Message- From: lala [mailto:l...@mail.theorb.net] Sent: Wednesday, April 14, 2010 10:15 AM To: Ashley M. Kirchner Cc: php-general@lists.php.net Subject: Re: [PHP] Array differences Ashley M. Kirchner wrote: $array1 = array(1, 2, 3, 4, 5, 6); $array2 = array(1, 3, 2, 8, 9); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); = (4, 5, 6, 8, 9) Hi Ash, Isn't the array_unique() unnecessary? Mike Thinking about it, it should be unnecessary, but at the same time I want to absolutely sure that I get unique values out of the two diffs. Ash -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Array differences
On Wed, Apr 14, 2010 at 7:01 AM, Ashley M. Kirchner ash...@pcraft.com wrote: I have the following scenario: $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $result = array_diff($array1, $array2); print_r($result); This returns: Array ( [1] = 34 [4] = 90 ) However what I really want is a two-way comparison. I want elements that don't exist in either to be returned: 34 and 90 because they don't exist in $array2, AND 23 and 89 because they don't exist in $array1. So, is that a two step process of first doing an array_diff($array1, $array2) then reverse it by doing array_diff($array2, $array1) and merge/unique the results? Any caveats with that? $array1 = array(12, 34, 56, 78, 90); $array2 = array(12, 23, 56, 78, 89); $diff1 = array_diff($array1, $array2); $diff2 = array_diff($array2, $array1); $result = array_unique(array_merge($diff1, $diff2)); print_r($result); -- A ok, adding this to the todo-list for htmlMicroscope... ETA on delivery of 1.3.0-final: about 2 to 3 months i'm afraid. Gotta get a new laundromat for my home too and stuff like that :) -- - Greetings from Rene7705, I have made some free open source webcomponents designed and written by me available through: http://code.google.com/u/rene7705/ , or http://mediabeez.ws (latest dev versions, currently offline) Personal info about me is available through http://www.facebook.com/rene7705 - -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array Search Problem
Hi, At the time when I am writing this, looks like I already got the functions I needed. It turned out that I had to use some array_combine, sorting the items by keys instead of values as well as using array_keys to get the values I needed. Thanks for pointing me towards the right direction. Alice From: rene7...@gmail.com Date: Thu, 11 Mar 2010 07:12:15 +0100 Subject: Re: [PHP] Array Search Problem To: aj...@alumni.iu.edu CC: php-general@lists.php.net (almost) all the tricks are in the comments of the help page for a function, on php.net but all functions accept only a given (and usually documented) set of parameter(type)s, so you'll probably have to prepare the var, or even call the function in a loop, outputting to yet another descriptively named array that'll be used as wanted list later in the code. On Wed, Mar 10, 2010 at 6:57 PM, Alice Wei aj...@alumni.iu.edu wrote: did you read the help for those functions on php.net? Yes, I found a recursive way to find out the index like I wanted, by doing something like $from = explode(-, $from); $state_colors= explode(-, $state_colors); $change = explode(-,$change); $count = count($new_array); $i=0; foreach ($new_array as $key = $value){ echo $i . . $key . is . $value . miles awaybr /; $i++; } You can see it is not very elegant, and plus, I created the $new_array so I could do the ordering according to the values of the change array. I can tell that since this is not a single array, which is probably why array_search does not work. Since I don't need the value of my new_array here, I am still finding out how to strip off the values here without having to flatten my array. Is what I am trying to do here possible? Or, is there a trick in array_search that I could use to find the index without having to strip off anything? Thanks for your help. Alice On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote: Hi, I have the code as shown in the following that I am trying to create the image of based on the file loaded into the file and additional edits. The problem here appears to be that no matter what value I have in the $distance_to_destination variable, it does not affect any changes on the map. What I am trying to do here is to create a map based on the pre-passed through colors of individual states from another program, but I have to match up the colors based on the values of the correct states. I figured that I may have problems with $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index Obviously, it is not applying the colors to the states that I would like other than doing it one by one as the order of what is in the $from variable. Could someone please give me some hints on how I could do the array_search here based on the value of the values in the $distance_to_distance and apply the color to the states? ?php header(Content-type: image/svg+xml); //Outputting an SVG $from = $_GET['from']; $state_colors= $_GET['state_colors']; $distance_to_destination= $_GET['distance_to_destination']; $from = explode(-, $from); $state_colors= explode(-, $state_colors); $change = explode(-,$change); #Load the Map $ourFileName= USA_Counties_with_FIPS_and_names.svg; $fh = fopen($ourFileName, r) or die(Can't open file); $contents = fread($fh,filesize($ourFileName)); $lines2= file($ourFileName); foreach ($lines2 as $line_num = $line2) { $style_line_num = $line_num+3; $line2 = trim($line2); if(preg_match(/^style/,$line2)) { $rest = substr($line2,0,-1); for ($j=$line_num;$j=$style_line_num;$j++){ if(preg_match(/inkscape:label/,$lines2[$j])) { $location = explode(=,$lines2[$j]); $location2 = substr($location[1],1,-6); if(in_array($location2, $from)) { $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index $rest2 = substr($line2,0,-1). $colors_style . \; echo $rest2 . \n; } else echo $line2 . \n; } //end preg_match inkscape } //end for loop } //If preg_match style else echo $line2 . \n; //else if preg_match style } //end for each fclose($fh); ? Thanks for your help. Alice _ Hotmail: Trusted email with Microsoft’s powerful SPAM protection. http://clk.atdmt.com/GBL/go/201469226/direct/01
Re: [PHP] Array Search Problem
did you read the help for those functions on php.net? On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote: Hi, I have the code as shown in the following that I am trying to create the image of based on the file loaded into the file and additional edits. The problem here appears to be that no matter what value I have in the $distance_to_destination variable, it does not affect any changes on the map. What I am trying to do here is to create a map based on the pre-passed through colors of individual states from another program, but I have to match up the colors based on the values of the correct states. I figured that I may have problems with $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index Obviously, it is not applying the colors to the states that I would like other than doing it one by one as the order of what is in the $from variable. Could someone please give me some hints on how I could do the array_search here based on the value of the values in the $distance_to_distance and apply the color to the states? ?php header(Content-type: image/svg+xml); //Outputting an SVG $from = $_GET['from']; $state_colors= $_GET['state_colors']; $distance_to_destination= $_GET['distance_to_destination']; $from = explode(-, $from); $state_colors= explode(-, $state_colors); $change = explode(-,$change); #Load the Map $ourFileName= USA_Counties_with_FIPS_and_names.svg; $fh = fopen($ourFileName, r) or die(Can't open file); $contents = fread($fh,filesize($ourFileName)); $lines2= file($ourFileName); foreach ($lines2 as $line_num = $line2) { $style_line_num = $line_num+3; $line2 = trim($line2); if(preg_match(/^style/,$line2)) { $rest = substr($line2,0,-1); for ($j=$line_num;$j=$style_line_num;$j++){ if(preg_match(/inkscape:label/,$lines2[$j])) { $location = explode(=,$lines2[$j]); $location2 = substr($location[1],1,-6); if(in_array($location2, $from)) { $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index $rest2 = substr($line2,0,-1). $colors_style . \; echo $rest2 . \n; } else echo $line2 . \n; } //end preg_match inkscape } //end for loop } //If preg_match style else echo $line2 . \n; //else if preg_match style } //end for each fclose($fh); ? Thanks for your help. Alice _ Hotmail: Trusted email with Microsoft’s powerful SPAM protection. http://clk.atdmt.com/GBL/go/201469226/direct/01/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Array Search Problem
did you read the help for those functions on php.net? Yes, I found a recursive way to find out the index like I wanted, by doing something like $from = explode(-, $from); $state_colors= explode(-, $state_colors); $change = explode(-,$change); $count = count($new_array); $i=0; foreach ($new_array as $key = $value){ echo $i . . $key . is . $value . miles awaybr /; $i++; } You can see it is not very elegant, and plus, I created the $new_array so I could do the ordering according to the values of the change array. I can tell that since this is not a single array, which is probably why array_search does not work. Since I don't need the value of my new_array here, I am still finding out how to strip off the values here without having to flatten my array. Is what I am trying to do here possible? Or, is there a trick in array_search that I could use to find the index without having to strip off anything? Thanks for your help. Alice On Wed, Mar 10, 2010 at 4:12 PM, Alice Wei aj...@alumni.iu.edu wrote: Hi, I have the code as shown in the following that I am trying to create the image of based on the file loaded into the file and additional edits. The problem here appears to be that no matter what value I have in the $distance_to_destination variable, it does not affect any changes on the map. What I am trying to do here is to create a map based on the pre-passed through colors of individual states from another program, but I have to match up the colors based on the values of the correct states. I figured that I may have problems with $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index Obviously, it is not applying the colors to the states that I would like other than doing it one by one as the order of what is in the $from variable. Could someone please give me some hints on how I could do the array_search here based on the value of the values in the $distance_to_distance and apply the color to the states? ?php header(Content-type: image/svg+xml); //Outputting an SVG $from = $_GET['from']; $state_colors= $_GET['state_colors']; $distance_to_destination= $_GET['distance_to_destination']; $from = explode(-, $from); $state_colors= explode(-, $state_colors); $change = explode(-,$change); #Load the Map $ourFileName= USA_Counties_with_FIPS_and_names.svg; $fh = fopen($ourFileName, r) or die(Can't open file); $contents = fread($fh,filesize($ourFileName)); $lines2= file($ourFileName); foreach ($lines2 as $line_num = $line2) { $style_line_num = $line_num+3; $line2 = trim($line2); if(preg_match(/^style/,$line2)) { $rest = substr($line2,0,-1); for ($j=$line_num;$j=$style_line_num;$j++){ if(preg_match(/inkscape:label/,$lines2[$j])) { $location = explode(=,$lines2[$j]); $location2 = substr($location[1],1,-6); if(in_array($location2, $from)) { $key= array_search($location2,$from); //Find out the position of the index in the array $colors_style = ;fill: . $state_colors[$key]; //Use the index from array_search to apply to the color index $rest2 = substr($line2,0,-1). $colors_style . \; echo $rest2 . \n; } else echo $line2 . \n; } //end preg_match inkscape } //end for loop } //If preg_match style else echo $line2 . \n; //else if preg_match style } //end for each fclose($fh); ? Thanks for your help. Alice _ Hotmail: Trusted email with Microsoft’s powerful SPAM protection. http://clk.atdmt.com/GBL/go/201469226/direct/01/ _ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/201469230/direct/01/