Re: [PHP] variable type - conversion/checking
Sorry if I'm missing something, there's a lot of replies after my first post on this thread. Is there something wrong with the floor() approach? I liked the regex solution but isn't it more expensive and more verbose than just doing a well commented is_numeric plus floor/ceil math? Just trying to understand the motivations behind the preferences. Thanks. On Sun, Mar 17, 2013 at 7:17 PM, Matijn Woudt tijn...@gmail.com wrote: On Sun, Mar 17, 2013 at 10:20 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: On 16-3-2013 19:20, Matijn Woudt wrote: On Sat, Mar 16, 2013 at 6:52 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg All responses in this thread have been very nice; but you could also try a much simpler 2-step check: 1. is_numeric 2. if true check if there's a decimal character in the string: if(is_numeric($str) false === strpos('.', $str)) { // it's an int for sure } else { // might be a number, but it's definitly not an int } Wrong. is_numeric will accept 1e1, which is a float, so you would need to check for e or E too. - Matijn Although in theory I agree, indeed any e* number is treated as a floating point number. However, considering the exponent and the base are forced to be integer numbers (due to exclusion of decimal points), in the real number system, you will *always* end up with a natural number, i.e. integer. Regardless of your input. So as a result, the input could always be interpreted as an integer, without any precision-loss using the method above. - Tul Except... that it might not fit in an 32 or 64 bit integer, which would lead to precision loss. - Matijn
Re: [PHP] variable type - conversion/checking
On 16-3-2013 19:20, Matijn Woudt wrote: On Sat, Mar 16, 2013 at 6:52 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg All responses in this thread have been very nice; but you could also try a much simpler 2-step check: 1. is_numeric 2. if true check if there's a decimal character in the string: if(is_numeric($str) false === strpos('.', $str)) { // it's an int for sure } else { // might be a number, but it's definitly not an int } Wrong. is_numeric will accept 1e1, which is a float, so you would need to check for e or E too. - Matijn Although in theory I agree, indeed any e* number is treated as a floating point number. However, considering the exponent and the base are forced to be integer numbers (due to exclusion of decimal points), in the real number system, you will *always* end up with a natural number, i.e. integer. Regardless of your input. So as a result, the input could always be interpreted as an integer, without any precision-loss using the method above. - Tul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On Sun, Mar 17, 2013 at 10:20 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: On 16-3-2013 19:20, Matijn Woudt wrote: On Sat, Mar 16, 2013 at 6:52 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg All responses in this thread have been very nice; but you could also try a much simpler 2-step check: 1. is_numeric 2. if true check if there's a decimal character in the string: if(is_numeric($str) false === strpos('.', $str)) { // it's an int for sure } else { // might be a number, but it's definitly not an int } Wrong. is_numeric will accept 1e1, which is a float, so you would need to check for e or E too. - Matijn Although in theory I agree, indeed any e* number is treated as a floating point number. However, considering the exponent and the base are forced to be integer numbers (due to exclusion of decimal points), in the real number system, you will *always* end up with a natural number, i.e. integer. Regardless of your input. So as a result, the input could always be interpreted as an integer, without any precision-loss using the method above. - Tul Except... that it might not fit in an 32 or 64 bit integer, which would lead to precision loss. - Matijn
Re: [PHP] variable type - conversion/checking
On Fri, Mar 15, 2013 at 8:34 PM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! The op wasn't about casting a string to an int but detecting if a string was just a string representation of an int. Hence using a regex to determine that. Regular expressions are not just about giving feedback to the user. Seemed to me that was exactly what it was about. 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] variable type - conversion/checking
On Fri, 2013-03-15 at 22:32 -0400, Andrew Ballard wrote: Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Shoot...I hadn't considered how PHP might handle hex or octal strings when casting to int. (Again, not in front of a computer where I can test it right now. ) Regexes have problems with more than 9 digits for 32-bit ints. I guess to some degree it depends on how likely you are to experience values that large. Andrew Do they? Regex's deal with strings, so I don't see why they should have such issues. I've certainly never come across that problem, or heard of it before. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] variable type - conversion/checking
On Mar 16, 2013 6:14 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Fri, 2013-03-15 at 22:32 -0400, Andrew Ballard wrote: Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Shoot...I hadn't considered how PHP might handle hex or octal strings when casting to int. (Again, not in front of a computer where I can test it right now. ) Regexes have problems with more than 9 digits for 32-bit ints. I guess to some degree it depends on how likely you are to experience values that large. Andrew Do they? Regex's deal with strings, so I don't see why they should have such issues. I've certainly never come across that problem, or heard of it before. Thanks, Ash http://www.ashleysheridan.co.uk Sure. If the string is nine or fewer digits, they can all be 0-9. If it is 10 digits, the first digit can only be 1-2. If it's 1, the remaining nine digits can still be 0-9, but if the first digit is 2, the second digit can only be 0-1. If the second digit is 0, the remaining eight digits can still be 0-9, but if it is 1, the third digit can only be 0-4. If the third digit is 0-3, the remaining seven digits can still be 0-9, but if it is 4, the fourth digit can only be 0-7. This pattern would continue for each of the remaining digits. Hopefully you get the idea. When you get to the final digit, its range depends not only on the nine preceding digits, but also the sign. If this is 64-bit, that adds even more wrinkles (including being aware of whether your implementation supports 64-bit ints). It may be possible to do with regular expressions, but it would definitely be complex and probably a time sink. As I said, if you KNOW you won't be dealing with integers that are more than nine digits, the regex should work fine. Remember, the OP didn't ask if it was an integer in the realm of infinite pure integers; he asked how to tell if a string was a number that could be converted to an int (presumably without loss). Andrew
Re: [PHP] variable type - conversion/checking
On Sat, 2013-03-16 at 11:46 -0400, Andrew Ballard wrote: On Mar 16, 2013 6:14 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Fri, 2013-03-15 at 22:32 -0400, Andrew Ballard wrote: Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Shoot...I hadn't considered how PHP might handle hex or octal strings when casting to int. (Again, not in front of a computer where I can test it right now. ) Regexes have problems with more than 9 digits for 32-bit ints. I guess to some degree it depends on how likely you are to experience values that large. Andrew Do they? Regex's deal with strings, so I don't see why they should have such issues. I've certainly never come across that problem, or heard of it before. Thanks, Ash http://www.ashleysheridan.co.uk Sure. If the string is nine or fewer digits, they can all be 0-9. If it is 10 digits, the first digit can only be 1-2. If it's 1, the remaining nine digits can still be 0-9, but if the first digit is 2, the second digit can only be 0-1. If the second digit is 0, the remaining eight digits can still be 0-9, but if it is 1, the third digit can only be 0-4. If the third digit is 0-3, the remaining seven digits can still be 0-9, but if it is 4, the fourth digit can only be 0-7. This pattern would continue for each of the remaining digits. Hopefully you get the idea. When you get to the final digit, its range depends not only on the nine preceding digits, but also the sign. If this is 64-bit, that adds even more wrinkles (including being aware of whether your implementation supports 64-bit ints). It may be possible to do with regular expressions, but it would definitely be complex and probably a time sink. As I said, if you KNOW you won't be dealing with integers that are more than nine digits, the regex should work fine. Remember, the OP didn't ask if it was an integer in the realm of infinite pure integers; he asked how to tell if a string was a number that could be converted to an int (presumably without loss). Andrew Ah, I see. I think that's not an issue as such with regular expressions having problems, more that bit limitations has a problem with numbers! Bearing that in mind, this does the trick: $string1 = '9'; $string2 = '99'; $string3 = '99'; var_dump($string === (intval($string1).'')); var_dump($string === (intval($string2).'')); var_dump($string === (intval($string3).'')); I'm getting the expected results on my machine (32-bit) but a 64-bit machine would get the correct results for larger numbers. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] variable type - conversion/checking
Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg All responses in this thread have been very nice; but you could also try a much simpler 2-step check: 1. is_numeric 2. if true check if there's a decimal character in the string: if(is_numeric($str) false === strpos('.', $str)) { // it's an int for sure } else { // might be a number, but it's definitly not an int } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On Sat, Mar 16, 2013 at 6:52 PM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg All responses in this thread have been very nice; but you could also try a much simpler 2-step check: 1. is_numeric 2. if true check if there's a decimal character in the string: if(is_numeric($str) false === strpos('.', $str)) { // it's an int for sure } else { // might be a number, but it's definitly not an int } Wrong. is_numeric will accept 1e1, which is a float, so you would need to check for e or E too. - Matijn
Re: [PHP] variable type - conversion/checking
On Sat, Mar 16, 2013 at 12:21 PM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Sat, 2013-03-16 at 11:46 -0400, Andrew Ballard wrote: On Mar 16, 2013 6:14 AM, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Fri, 2013-03-15 at 22:32 -0400, Andrew Ballard wrote: Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Shoot...I hadn't considered how PHP might handle hex or octal strings when casting to int. (Again, not in front of a computer where I can test it right now. ) Regexes have problems with more than 9 digits for 32-bit ints. I guess to some degree it depends on how likely you are to experience values that large. Andrew Do they? Regex's deal with strings, so I don't see why they should have such issues. I've certainly never come across that problem, or heard of it before. Thanks, Ash http://www.ashleysheridan.co.uk Sure. If the string is nine or fewer digits, they can all be 0-9. If it is 10 digits, the first digit can only be 1-2. If it's 1, the remaining nine digits can still be 0-9, but if the first digit is 2, the second digit can only be 0-1. If the second digit is 0, the remaining eight digits can still be 0-9, but if it is 1, the third digit can only be 0-4. If the third digit is 0-3, the remaining seven digits can still be 0-9, but if it is 4, the fourth digit can only be 0-7. This pattern would continue for each of the remaining digits. Hopefully you get the idea. When you get to the final digit, its range depends not only on the nine preceding digits, but also the sign. If this is 64-bit, that adds even more wrinkles (including being aware of whether your implementation supports 64-bit ints). It may be possible to do with regular expressions, but it would definitely be complex and probably a time sink. As I said, if you KNOW you won't be dealing with integers that are more than nine digits, the regex should work fine. Remember, the OP didn't ask if it was an integer in the realm of infinite pure integers; he asked how to tell if a string was a number that could be converted to an int (presumably without loss). Andrew Ah, I see. I think that's not an issue as such with regular expressions having problems, more that bit limitations has a problem with numbers! ANY computer system is going to have limitations with numbers -- you can't store infinity in a finite system. LOL Bearing that in mind, this does the trick: $string1 = '9'; $string2 = '99'; $string3 = '99'; var_dump($string === (intval($string1).'')); var_dump($string === (intval($string2).'')); var_dump($string === (intval($string3).'')); That's the same thing I posted, just different syntax. You are still converting the string to an int, converting the int back to a string, and comparing the resulting value to the original string using the identical (===) operator. Depending on one's needs, it could be tweaked a little to handle leading/trailing spaces, leading zeroes, etc. function is_int_hiding_as_string($value) { if (is_string($value)) { // remove any spaces around the value. $value = trim($value); // check for a sign :-) $sign = (substr($value, 0, 1) === '-') ? '-' : ''; // strip off the sign, any additional leading spaces or zeroes $value = ltrim($value, ' 0-'); // I didn't strip off trailing zeroes after the decimal because // I consider that a loss of precision, but you could do so // if necessary. return ($value === $sign . (int)$value); } return false; } I'm getting the expected results on my machine (32-bit) but a 64-bit machine would get the correct results for larger numbers. As I understood the original post, these ARE the correct results on ANY system. If the string value can be safely converted to an int *in the environment under which the script is executing* without loss of precision, this will return true; if it cannot, it returns false. Sorry for getting carried away, but it is SO much easier to respond on an actual keyboard than my phone. :-) Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On 15/03/13 06:21, Jim Lucas wrote: On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim Integers can be negative too: I suspect your test would reject a leading '-'... -- Peter Ford, Developer phone: 01580 89 fax: 01580 893399 Justcroft International Ltd. www.justcroft.com Justcroft House, High Street, Staplehurst, Kent TN12 0AH United Kingdom Registered in England and Wales: 2297906 Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XS -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: On Fri, Mar 15, 2013 at 3:55 AM, Peter Ford p...@justcroft.com wrote: On 15/03/13 06:21, Jim Lucas wrote: On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim Integers can be negative too: I suspect your test would reject a leading '-'... For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] variable type - conversion/checking
On 15/03/2013 22:00, Ashley Sheridan wrote: On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int I'm late in on this thread so apologies if I have missed something here .. but wouldn't is_int() do what the OP wants? rich -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On 03/15/2013 02:33 PM, richard gray wrote: On 15/03/2013 22:00, Ashley Sheridan wrote: On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int I'm late in on this thread so apologies if I have missed something here .. but wouldn't is_int() do what the OP wants? rich Nope, because the OP wants to test if a variable, that is a string, could be converted to an integer. Not if a variable is an integer. -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On Fri, Mar 15, 2013 at 4:00 PM, Ashley Sheridan a...@ashleysheridan.co.ukwrote: ** On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: On Fri, Mar 15, 2013 at 3:55 AM, Peter Ford p...@justcroft.com wrote: On 15/03/13 06:21, Jim Lucas wrote: On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim Integers can be negative too: I suspect your test would reject a leading '-'... For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int Thanks, Ash http://www.ashleysheridan.co.uk That is so about is_numeric(), but once I know it's a numeric, coercing it to just an int is easy. *Validating*, rather than just assuring, that a string is an integer is another matter; if you need to give feedback to the user, etc., in which case a Regex is better. (One small nit, + is possible on integers, too.)
Re: [PHP] variable type - conversion/checking
tamouse mailing lists tamouse.li...@gmail.com wrote: On Fri, Mar 15, 2013 at 4:00 PM, Ashley Sheridan a...@ashleysheridan.co.ukwrote: ** On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: On Fri, Mar 15, 2013 at 3:55 AM, Peter Ford p...@justcroft.com wrote: On 15/03/13 06:21, Jim Lucas wrote: On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim Integers can be negative too: I suspect your test would reject a leading '-'... For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int Thanks, Ash http://www.ashleysheridan.co.uk That is so about is_numeric(), but once I know it's a numeric, coercing it to just an int is easy. *Validating*, rather than just assuring, that a string is an integer is another matter; if you need to give feedback to the user, etc., in which case a Regex is better. (One small nit, + is possible on integers, too.) The op wasn't about casting a string to an int but detecting if a string was just a string representation of an int. Hence using a regex to determine that. Regular expressions are not just about giving feedback to the user. 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] variable type - conversion/checking
I suppose one could try something like this: if (is_string($val) $val === (string)(int)$val) If $val is an integer masquerading as a string, it should be identical to the original string when cast back to a string, shouldn't it? (I can't try it right now.) Andrew
Re: [PHP] variable type - conversion/checking
2013/3/16 Ashley Sheridan a...@ashleysheridan.co.uk tamouse mailing lists tamouse.li...@gmail.com wrote: On Fri, Mar 15, 2013 at 4:00 PM, Ashley Sheridan a...@ashleysheridan.co.ukwrote: ** On Fri, 2013-03-15 at 04:57 -0500, tamouse mailing lists wrote: On Fri, Mar 15, 2013 at 3:55 AM, Peter Ford p...@justcroft.com wrote: On 15/03/13 06:21, Jim Lucas wrote: On 3/14/2013 4:05 PM, Matijn Woudt wrote: On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.casting http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn H... Interesting. Looking back at my code base where I thought I was doing that, turns out the final results were not that, but this: $value = asdf1234; if ( $value === (string)intval($value) ) { Looking back at the OP's request and after a little further searching, it seems that there might be a better possible solution for what the OP is requesting. ?php $values = array(asdf1234, 123.123, 123); foreach ( $values AS $value ) { echo $value; if ( ctype_digit($value) ) { echo ' - is all digits'; } else { echo ' - is NOT all digits'; } echo 'br /'.PHP_EOL; } returns... asdf1234 - is NOT all digits 123.123 - is NOT all digits 123 - is all digits http://www.php.net/manual/en/function.ctype-digit.php An important note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual. -- Jim Integers can be negative too: I suspect your test would reject a leading '-'... For my money, `is_numeric()` does just what I want. The thing is, is_numeric() will not check if a string is a valid int, but any valid number, including a float. For something like this, wouldn't a regex be better? if(preg_match('/^\-?\d+$/', $string)) echo int Thanks, Ash http://www.ashleysheridan.co.uk That is so about is_numeric(), but once I know it's a numeric, coercing it to just an int is easy. *Validating*, rather than just assuring, that a string is an integer is another matter; if you need to give feedback to the user, etc., in which case a Regex is better. (One small nit, + is possible on integers, too.) The op wasn't about casting a string to an int but detecting if a string was just a string representation of an int. Hence using a regex to determine that. Regular expressions are not just about giving feedback to the user. Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Thanks, Ash http://www.ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- github.com/KingCrunch
Re: [PHP] variable type - conversion/checking
2013/3/16 Andrew Ballard aball...@gmail.com I suppose one could try something like this: if (is_string($val) $val === (string)(int)$val) If $val is an integer masquerading as a string, it should be identical to the original string when cast back to a string, shouldn't it? (I can't try it right now.) It is semantically equivalent to $val == (int) $val and as far as I remember (I didn't read everything completely) this were mentioned. I didn't read, whether or not, it was accepted as solution ;) Andrew -- github.com/KingCrunch
Re: [PHP] variable type - conversion/checking
On Mar 15, 2013 9:54 PM, Sebastian Krebs krebs@gmail.com wrote: 2013/3/16 Andrew Ballard aball...@gmail.com I suppose one could try something like this: if (is_string($val) $val === (string)(int)$val) If $val is an integer masquerading as a string, it should be identical to the original string when cast back to a string, shouldn't it? (I can't try it right now.) It is semantically equivalent to $val == (int) $val and as far as I remember (I didn't read everything completely) this were mentioned. I didn't read, whether or not, it was accepted as solution ;) Not quite. That method will massage both values to the same type for the comparison. Whoever shot it down said they both go to int. If that's the case, if ($val == (int)$val) is more like saying if ((int)$val === (int)$val) What I suggested converts the string to an int, the resulting int back to a string, then does a type-specific comparison to the original string value. Andrew
Re: [PHP] variable type - conversion/checking
Guess regex are the only useful solution here. When you consider to use built-in functions, just remember, that for example '0xAF' is an integer too, but '42.00' isn't. Shoot...I hadn't considered how PHP might handle hex or octal strings when casting to int. (Again, not in front of a computer where I can test it right now. ) Regexes have problems with more than 9 digits for 32-bit ints. I guess to some degree it depends on how likely you are to experience values that large. Andrew
Re: [PHP] variable type - conversion/checking
On Sat, Mar 16, 2013 at 2:54 AM, Sebastian Krebs krebs@gmail.comwrote: 2013/3/16 Andrew Ballard aball...@gmail.com I suppose one could try something like this: if (is_string($val) $val === (string)(int)$val) If $val is an integer masquerading as a string, it should be identical to the original string when cast back to a string, shouldn't it? (I can't try it right now.) It is semantically equivalent to $val == (int) $val and as far as I remember (I didn't read everything completely) this were mentioned. I didn't read, whether or not, it was accepted as solution ;) Sebastian, This is not true. $val === (string)(int)$val will do a string compare, where as $val == (int) $val will do an integer compare, which will convert the left hand to integer too. Your equation will always evaluate as true. Andrews' solution should work too, but it depends on what you accept as integer, in this case you would be able to parse normal numbers, with optionally a sign and extra 0's in front. is_numeric will parse those integers, but also hexadecimal, octal and binary notations, and parses floating point integers. If you don't want the floating points, you could add an extra check that verifies it is not a float. - Matijn
[PHP] variable type - conversion/checking
Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg
Re: [PHP] variable type - conversion/checking
On Thu, Mar 14, 2013 at 7:02 PM, georg georg.chamb...@telia.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn
Re: [PHP] variable type - conversion/checking
Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudt tijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georg georg.chamb...@telia.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn
Re: [PHP] variable type - conversion/checking
On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable type - conversion/checking
On Thu, Mar 14, 2013 at 11:44 PM, Jim Lucas li...@cmsws.com wrote: On 03/14/2013 11:50 AM, Samuel Lopes Grigolato wrote: Something like if (is_numeric($var) $var == floor($var)) will do the trick. I don't know if there's a better (more elegant) way. On Thu, Mar 14, 2013 at 3:09 PM, Matijn Woudttijn...@gmail.com wrote: On Thu, Mar 14, 2013 at 7:02 PM, georggeorg.chamb...@telia.com** wrote: Hi, I have tried to find a way to check if a character string is possible to test whether it is convertible to an intger ! any suggestion ? BR georg You could use is_numeric for that, though it also accepts floats. - Matijn for that type of test I have always used this: if ( $val == (int)$val ) { http://www.php.net/manual/en/**language.types.integer.php#** language.types.integer.castinghttp://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting I hope you're not serious about this... When comparing a string and an int, PHP will translate the string to int too, and of course they will always be equal then. So: $a = abc; if($a == (int)$a) echo YES; else echo NO; Will always return YES. - Matijn
RE: [PHP] variable placeholders in a text file
On Sat, 5 Jan 2013 04:20:09 -0600, Kevin Kinsey wrote: Nelson (et al), I've enjoyed reading this thread and apologize for dredging it up. It's interesting to see your progression of thought and the templating discussion is indeed a worthy one. However, I wanted to answer this objection from your initial message: The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. You *don't* have to; str_replace() is perfectly capable of handling arrays: = $replace = array(USER,SITENAME,SOME_CONSTANT); $replacements = array($user,$site_name,$foo); $replaced = str_replace($replace,$replacements,file_get_contents(/somefile.txt)); = This, of course, doesn't negate a good templating system* ... but it's handy to know and you'll probably use it sooner or later. Kevin Kinsey P.S. *assuming that's not an oxymoron! Kevin, No apologies necessary, at least not to me. I always appreciate help and I probably wouldn't have figured out your way on my own, at least not in relation to what I am trying to do. And you've just proved once again that there is almost always more than one way to accomplish a goal. I like this solution as much as what I ended up with and will keep it handy. Thanks! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
On Mon, Dec 31, 2012 at 02:29:38PM -0600, Nelson Green wrote: On Mon, 31 Dec 2012 19:59:02, Ashley Sheridan wrote: ___ On Mon, 2012-12-31 at 13:39 -0600, Nelson Green wrote: snip snip Nelson (et al), I've enjoyed reading this thread and apologize for dredging it up. It's interesting to see your progression of thought and the templating discussion is indeed a worthy one. However, I wanted to answer this objection from your initial message: The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. You *don't* have to; str_replace() is perfectly capable of handling arrays: = $replace = array(USER,SITENAME,SOME_CONSTANT); $replacements = array($user,$site_name,$foo); $replaced = str_replace($replace,$replacements,file_get_contents(/somefile.txt)); = This, of course, doesn't negate a good templating system* ... but it's handy to know and you'll probably use it sooner or later. Kevin Kinsey P.S. *assuming that's not an oxymoron! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] variable placeholders in a text file
While using the *_once works in many cases, if you're doing a mass mailing kind of thing, you want to use the standard include/require so you can re-include it as your variables change: foreach ($customers as $customer) { $fullname = $customer['fullname']; $address = $customer['address']; // and so on include(mailing.php); process($mailing,$customer); } where mailing.php defines the $mailing variable as the content that got included and substituted. (Back before I came up with this, I was starting off in the same place as the OP -- and then I just realized wait --- PHP *IS* a templating system! a voila) For what I am trying to do here, I think what I'm doing will suffice. Like you did, I am going through the learning process. What I've read about templating has whetted my appetite for bigger and better things, but I should probably finish this first. Right now I'm just trying to personalize a rather dry page just a bit. Thanks! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] variable placeholders in a text file
Hello, I have created a simple function that prints a personalized greeting by reading the greeting contents from a file. I pass the user's name to the function, and the function reads the file contents into a string variable. I am then using str_replace to replace the word USER in the string with the user's name that was passed to the function. Then the function correctly prints the personalized greeting as I wish. My question is, is there another way to do something similar, such as embedding a variable name directly into the text file? In other words, instead of my text file reading: Hello USER ... Can I do something like this: Hello $user_name ... and then write my function to replace $user_name with the passed parameter prior to printing? The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. Plus the latter seems to be a more robust way of making the changes. Thanks, and apologies if this has been asked before and I missed it. I'm just not sure how to phrase this for a search engine. Nelson
Re: [PHP] variable placeholders in a text file
Yes! Easy standard stuff. $title = 'Mr.; $user_name = 'John Doe'; $message = Hello $title $user_name Just define the value for the variables before defining the value for the message. Note that $message has to use double quotes for the expansion. Also consider using HEREDOC instead of the double quotes. You may want to put your message in a text file and using the include function. On 12-12-31 02:39 PM, Nelson Green wrote: Hello, I have created a simple function that prints a personalized greeting by reading the greeting contents from a file. I pass the user's name to the function, and the function reads the file contents into a string variable. I am then using str_replace to replace the word USER in the string with the user's name that was passed to the function. Then the function correctly prints the personalized greeting as I wish. My question is, is there another way to do something similar, such as embedding a variable name directly into the text file? In other words, instead of my text file reading: Hello USER ... Can I do something like this: Hello $user_name ... and then write my function to replace $user_name with the passed parameter prior to printing? The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. Plus the latter seems to be a more robust way of making the changes. Thanks, and apologies if this has been asked before and I missed it. I'm just not sure how to phrase this for a search engine. Nelson -- Stephen -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
On Mon, 2012-12-31 at 13:39 -0600, Nelson Green wrote: Hello, I have created a simple function that prints a personalized greeting by reading the greeting contents from a file. I pass the user's name to the function, and the function reads the file contents into a string variable. I am then using str_replace to replace the word USER in the string with the user's name that was passed to the function. Then the function correctly prints the personalized greeting as I wish. My question is, is there another way to do something similar, such as embedding a variable name directly into the text file? In other words, instead of my text file reading: Hello USER ... Can I do something like this: Hello $user_name ... and then write my function to replace $user_name with the passed parameter prior to printing? The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. Plus the latter seems to be a more robust way of making the changes. Thanks, and apologies if this has been asked before and I missed it. I'm just not sure how to phrase this for a search engine. Nelson You could use an existing templating solution, like Smarty, although for what you want to do it might be overkill. A few str_replace() calls shouldn't produce too much overhead, but it depends on the size of the text string in question. If it's just a couple of paragraphs of text, no problem, something closer to a whole chapter of a book will obviously be more expensive. You could try eval() on the block of text, but if you do, be really careful about what text you're using. I wouldn't recommend this if you're using any text supplied by a user. As a last option, you could have the text stored as separate parts which you join together in one string later. This might be less expensive in terms of processing power required, but it also makes maintenance more of a hassle later. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] variable placeholders in a text file
Please excuse the top post, but this may be helpful: http://stut.net/2008/10/28/snippet-simple-templates-with-php/ -Stuart -- Sent from my leaf blower On 31 Dec 2012, at 19:59, Ashley Sheridan a...@ashleysheridan.co.uk wrote: On Mon, 2012-12-31 at 13:39 -0600, Nelson Green wrote: Hello, I have created a simple function that prints a personalized greeting by reading the greeting contents from a file. I pass the user's name to the function, and the function reads the file contents into a string variable. I am then using str_replace to replace the word USER in the string with the user's name that was passed to the function. Then the function correctly prints the personalized greeting as I wish. My question is, is there another way to do something similar, such as embedding a variable name directly into the text file? In other words, instead of my text file reading: Hello USER ... Can I do something like this: Hello $user_name ... and then write my function to replace $user_name with the passed parameter prior to printing? The reason I ask is because I am going to want to do three substitutions, and I'd rather not do three str_replace calls if I don't have to. Plus the latter seems to be a more robust way of making the changes. Thanks, and apologies if this has been asked before and I missed it. I'm just not sure how to phrase this for a search engine. Nelson You could use an existing templating solution, like Smarty, although for what you want to do it might be overkill. A few str_replace() calls shouldn't produce too much overhead, but it depends on the size of the text string in question. If it's just a couple of paragraphs of text, no problem, something closer to a whole chapter of a book will obviously be more expensive. You could try eval() on the block of text, but if you do, be really careful about what text you're using. I wouldn't recommend this if you're using any text supplied by a user. As a last option, you could have the text stored as separate parts which you join together in one string later. This might be less expensive in terms of processing power required, but it also makes maintenance more of a hassle later. Thanks, Ash http://www.ashleysheridan.co.uk
RE: [PHP] variable placeholders in a text file
On Mon, 31 Dec 2012 19:59:02, Ashley Sheridan wrote: ___ On Mon, 2012-12-31 at 13:39 -0600, Nelson Green wrote: My question is, is there another way to do something similar, such as embedding a variable name directly into the text file? In other words, instead of my text file reading: Hello USER ... Can I do something like this: Hello $user_name ... and then write my function to replace $user_name with the passed parameter prior to printing? You could use an existing templating solution, like Smarty, although for what you want to do it might be overkill. A few str_replace() calls shouldn't produce too much overhead, but it depends on the size of the text string in question. You could try eval() on the block of text, but if you do, be really careful about what text you're using. I wouldn't recommend this if you're using any text supplied by a user. As a last option, you could have the text stored as separate parts which you join together in one string later. This might be less expensive in terms of processing power required, but it also makes maintenance more of a hassle later. Thanks, Ash http://www.ashleysheridan.co.uk Hi Ash, Yep, smarty would be way more than I need right now. I'm just dabbling with various things, trying to learn more about PHP. And my first thought was to split the components, which worked fine. Then I tried a HEREDOC which did allow variable substitution. This attempt is a move up from that, trying to generalize things a bit more. My input will be 100% generated by me, but in the back of my mind I'm looking towards the ability to use user supplied strings. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] variable placeholders in a text file
On Mon, 31 Dec 2012 14:47:20 Stephen D wrote: Yes! Easy standard stuff. $title = 'Mr.; $user_name = 'John Doe'; $message = Hello $title $user_name Just define the value for the variables before defining the value for the message. Note that $message has to use double quotes for the expansion. Also consider using HEREDOC instead of the double quotes. You may want to put your message in a text file and using the include function. Hi Stephen, My message is in a text file, but I'm using fopen and fread in a self-defined function, so message is actually defined as (GREETER_FILE is a defined constant): function print_greeting($user_name) { $handle = fopen(GREETER_FILE, r); $message = fread($file_handle, filesize(GREETER_FILE)); $msg_text = str_replace(USER, $user_name, $message); print($msg_txt); } And my text file is simply: $cat greet.txt Hello USER. How are you today? If I change USER to $user_name in the text file and change the print function parameter to $message, $user_name gets printed verbatim. In other words the greeting on my page becomes: Hello $user_name. How are you today? I want to pass the name Nelson to the function, and have it output: Hello Nelson. How are you today? after the function reads in text file input that contains a variable placeholder for the user name. I actually had a HEREDOC in the function, and that worked. But by reading a file instead, I can make things more flexible. I'd rather be changing a text file instead of a code file. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
On Mon, Dec 31, 2012 at 2:37 PM, Nelson Green nelsongree...@hotmail.com wrote: On Mon, 31 Dec 2012 14:47:20 Stephen D wrote: Yes! Easy standard stuff. $title = 'Mr.; $user_name = 'John Doe'; $message = Hello $title $user_name Just define the value for the variables before defining the value for the message. Note that $message has to use double quotes for the expansion. Also consider using HEREDOC instead of the double quotes. You may want to put your message in a text file and using the include function. Hi Stephen, My message is in a text file, but I'm using fopen and fread in a self-defined function, so message is actually defined as (GREETER_FILE is a defined constant): function print_greeting($user_name) { $handle = fopen(GREETER_FILE, r); $message = fread($file_handle, filesize(GREETER_FILE)); $msg_text = str_replace(USER, $user_name, $message); print($msg_txt); } And my text file is simply: $cat greet.txt Hello USER. How are you today? If I change USER to $user_name in the text file and change the print function parameter to $message, $user_name gets printed verbatim. In other words the greeting on my page becomes: Hello $user_name. How are you today? I want to pass the name Nelson to the function, and have it output: Hello Nelson. How are you today? after the function reads in text file input that contains a variable placeholder for the user name. I actually had a HEREDOC in the function, and that worked. But by reading a file instead, I can make things more flexible. I'd rather be changing a text file instead of a code file. I use the include(template) method for this alla time, it works great. Most especially for HTML emails coming from a web site to a group of users, just slick as anything. include does basically just what your print_greeting function does less the actual printout, but using php variables instead of a str_replace. Also, this way the templates can be stored elsewhere, outside the actual code base if need be. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
Bastien Koert On 2012-12-31, at 4:58 PM, tamouse mailing lists tamouse.li...@gmail.com wrote: On Mon, Dec 31, 2012 at 2:37 PM, Nelson Green nelsongree...@hotmail.com wrote: On Mon, 31 Dec 2012 14:47:20 Stephen D wrote: Yes! Easy standard stuff. $title = 'Mr.; $user_name = 'John Doe'; $message = Hello $title $user_name Just define the value for the variables before defining the value for the message. Note that $message has to use double quotes for the expansion. Also consider using HEREDOC instead of the double quotes. You may want to put your message in a text file and using the include function. Hi Stephen, My message is in a text file, but I'm using fopen and fread in a self-defined function, so message is actually defined as (GREETER_FILE is a defined constant): function print_greeting($user_name) { $handle = fopen(GREETER_FILE, r); $message = fread($file_handle, filesize(GREETER_FILE)); $msg_text = str_replace(USER, $user_name, $message); print($msg_txt); } And my text file is simply: $cat greet.txt Hello USER. How are you today? If I change USER to $user_name in the text file and change the print function parameter to $message, $user_name gets printed verbatim. In other words the greeting on my page becomes: Hello $user_name. How are you today? I want to pass the name Nelson to the function, and have it output: Hello Nelson. How are you today? after the function reads in text file input that contains a variable placeholder for the user name. I actually had a HEREDOC in the function, and that worked. But by reading a file instead, I can make things more flexible. I'd rather be changing a text file instead of a code file. I use the include(template) method for this alla time, it works great. Most especially for HTML emails coming from a web site to a group of users, just slick as anything. include does basically just what your print_greeting function does less the actual printout, but using php variables instead of a str_replace. Also, this way the templates can be stored elsewhere, outside the actual code base if need be. This is exactly what I do. Dead simple fast and the templates are fully self contained. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] variable placeholders in a text file
On 2012-12-31, at 4:58 PM, tamouse mailing lists tamouse.li...@gmail.com wrote: I use the include(template) method for this alla time, it works great. Most especially for HTML emails coming from a web site to a group of users, just slick as anything. include does basically just what your print_greeting function does less the actual printout, but using php variables instead of a str_replace. Also, this way the templates can be stored elsewhere, outside the actual code base if need be. This sounds like it might be what I'm looking for. If I'm understanding correctly, you are saying to use the include function to read in my greeting file. I think I've got the basic gist of the concept, and will see what I can hobble together real quick. This thought had not occurred to me. Thanks! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
On 12-12-31 03:37 PM, Nelson Green wrote: On Mon, 31 Dec 2012 14:47:20 Stephen D wrote: Yes! Easy standard stuff. $title = 'Mr.; $user_name = 'John Doe'; $message = Hello $title $user_name Just define the value for the variables before defining the value for the message. Note that $message has to use double quotes for the expansion. Also consider using HEREDOC instead of the double quotes. You may want to put your message in a text file and using the include function. Hi Stephen, My message is in a text file, but I'm using fopen and fread in a self-defined function, so message is actually defined as (GREETER_FILE is a defined constant): function print_greeting($user_name) { $handle = fopen(GREETER_FILE, r); $message = fread($file_handle, filesize(GREETER_FILE)); $msg_text = str_replace(USER, $user_name, $message); print($msg_txt); } And my text file is simply: $cat greet.txt Hello USER. How are you today? If I change USER to $user_name in the text file and change the print function parameter to $message, $user_name gets printed verbatim. In other words the greeting on my page becomes: Hello $user_name. How are you today? I want to pass the name Nelson to the function, and have it output: Hello Nelson. How are you today? after the function reads in text file input that contains a variable placeholder for the user name. I actually had a HEREDOC in the function, and that worked. But by reading a file instead, I can make things more flexible. I'd rather be changing a text file instead of a code file. The reason you get $user_name printed is because of the way you are populating the variable $message. You need to have $user_name embedded in double quotes or a HEREDOC when PHP parses $messsage. And $user_name has to have already been defined. Here is a sample from one of my sites. It is a simple one for the contact page. =contact.php ?php $thispage = Contact; $contenttop = p$thispage/p; $contentbody = HEREDOC pstep...@roissy.ca/p HEREDOC; require_once include.php; require_once utilities.php; echo $header . $markup; = The common stuff for every page is defined in the file include.php. I define the variable $markup in that file. Here is the definition for $markup $markup=HEREDOC body div id=all div id=top img src=$titlepng alt=$title / /div div id=main div id=mainrow div id=left $leftimage div id=mainnav ul $menu /ul /div /div div id=content div id=content-top $contenttop /div div id=content-body $contentbody /div div id=content-bottom /div /div /div /div div id=footer $copyright /div /div /body /html HEREDOC; There is lots more code, but this is the important stuff. By using require_once instead of fopen and fread, I have simpler code and PHP evaluates the embedded variables in $markup without any need to use string functions. In your case, I would make the file greeter.php =greeter.php=== $message = Hello $user_name. How are you today? === You replace the fopen and fread stuff with a require_once function and $message gets included and the user name resolved all in one line of code. Hope this helps -- Stephen -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] variable placeholders in a text file
On Mon, Dec 31, 2012 at 5:47 PM, Stephen stephe...@rogers.com wrote: The common stuff for every page is defined in the file include.php. I define the variable $markup in that file. Here is the definition for $markup $markup=HEREDOC [[snippy]] HEREDOC; By using require_once instead of fopen and fread, I have simpler code and PHP evaluates the embedded variables in $markup without any need to use string functions. While using the *_once works in many cases, if you're doing a mass mailing kind of thing, you want to use the standard include/require so you can re-include it as your variables change: foreach ($customers as $customer) { $fullname = $customer['fullname']; $address = $customer['address']; // and so on include(mailing.php); process($mailing,$customer); } where mailing.php defines the $mailing variable as the content that got included and substituted. (Back before I came up with this, I was starting off in the same place as the OP -- and then I just realized wait --- PHP *IS* a templating system! a voila) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable representation
I am trying to represent the variable: $row['Bible_knowledge_phrase_solver_game_question_topics_1'] Where the # 1 is replaced by a variable --- $i The following code executes without an error, but “Hello world” doesn’t show on the screen. ?php $row['Bible_knowledge_phrase_solver_game_question_topics_1'] = hello world; $i = 1; echo ${row['Bible_knowledge_phrase_solver_game_question_topics_$i']}; ? What needs to change? Ron Ron Piggott www.TheVerseOfTheDay.info
RE: [PHP] Variable representation
-Original Message- From: Ron Piggott [mailto:ron.pigg...@actsministries.org] Sent: Thursday, June 21, 2012 3:47 AM To: php-general@lists.php.net Subject: [PHP] Variable representation I am trying to represent the variable: $row['Bible_knowledge_phrase_solver_game_question_topics_1'] Where the # 1 is replaced by a variable --- $i The following code executes without an error, but “Hello world” doesn’t show on the screen. ?php $row['Bible_knowledge_phrase_solver_game_question_topics_1'] = hello world; $i = 1; echo ${row['Bible_knowledge_phrase_solver_game_question_topics_$i']}; ? What needs to change? Ron Ron Piggott www.TheVerseOfTheDay.info You can do this echo $row['Bible_knowledge_phrase_solver_game_question_topics_'.$i]; I would not suggest a variable name that long. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
or you can do this echo $row[Bible_knowledge_phrase_solver_game_question_topics_$i];
[PHP] Variable Question
I am trying to assign variables from an array into variables. This is following a database query. Right now they are in an array: $row[‘word_1’] $row[‘word_2’] $row[‘word_3’] ... $row[‘word_25’] I am trying to use this while look to assign them to variables: $word_1 $word_2 $word_3 ... $word_25 This is the WHILE loop: $i = 1; while ( $i = 25 ) { ${'word_'.$i} = stripslashes( eval (echo $row['word_$i']) ); ++$i; } What is confusing me is I don’t know how to represent the array variable. The specific error message I am receiving is: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING Can anyone see what I have done wrong and help me correct it? Thank you. Ron Ron Piggott www.TheVerseOfTheDay.info
Re: [PHP] Variable Question
On 19 Apr 2012, at 15:46, Ron Piggott wrote: I am trying to assign variables from an array into variables. This is following a database query. Right now they are in an array: $row[‘word_1’] $row[‘word_2’] $row[‘word_3’] ... $row[‘word_25’] Why those indices? Why isn't it just a numerically indexed array? I am trying to use this while look to assign them to variables: $word_1 $word_2 $word_3 ... $word_25 The first question that comes to mind is why the heck you would want to do such a thing? ${'word_'.$i} = stripslashes( eval (echo $row['word_$i']) ); Eww, nasty. Why the eval? Why not just stripslashes($row['word_'.$i])? Variable variables have their uses, but this seems to be one of those cases where you're trying to get the square peg through the triangular hole. Take a step back and give us some more context. -Stuart -- Stuart Dallas 3ft9 Ltd http://3ft9.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Question
I am trying to use this while look to assign them to variables: $word_1 $word_2 $word_3 ... $word_25 This should work for you: http://us3.php.net/manual/en/function.extract.php thnx, Christoph -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Question
On 04/19/2012 09:55 AM, Christoph Boget wrote: I am trying to use this while look to assign them to variables: $word_1 $word_2 $word_3 ... $word_25 This should work for you: http://us3.php.net/manual/en/function.extract.php thnx, Christoph Yes and you can use array_map('stripslashes', $row) prior. However I would just use the $row array as most people do instead of extracting. -- 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] Variable representation
On 02-04-2012 07:15, tamouse mailing lists wrote: As for doing what you originally asked, that requires doing an eval() on the statement utilizing string interpolation, like so: eval('echo image $i is $image_' . $i . '.PHP_EOL;'); but I think that's a bit harder to read and understand what's going on. When you have to add in escaped quotes and such, it gets much hairier. To utilize it in the loop you have above, I'd split the echoes up: echo lia href=\http://www.theverseoftheday.info/store-images/;; eval ('echo $image_ . $i;'); echo \ title=\Image . $i . \Image . $i . /a/li\r\n; so that the eval portion is doing only what needs to be interpolated and evaled. The rest of the output is fine the way it is. Note that if you did this: echo lia href=\http://www.theverseoftheday.info/store-images/; . eval('echo $image_ . $i;') . \ title=\Image . $i . \Image . $i ./a/li\r\n; the part in the eval would get written out first, then the rest of the echoed string, which is why you would need to split them up first. Generally, I think it's best to completely avoid using eval unless there is no other way to do what you want. Usually if you think you need to use eval: think again. In this case, it again holds true. Instead of doing what you do, you can also reference the variable as: echo ${'image_'.$i}; or echo $GLOBALS['image_'.$i]; Both are preferable by far over using eval, with all its potential security concerns. As for the original threat-author's request. I agree with you that a simple bit of code as below should work fine: foreach(range(1,4) as $i) { if(strlen($img=trim($row['image_'.$i])) 0) { echo 'li', 'a href=http://example.com/path/'.$img.'', 'Image '.$i, '/a', '/li', PHP_EOL; } } [and yes, I prefer using comma notation in echo to split it into clear, readable parts] - Tul -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
On Mon, Apr 2, 2012 at 4:34 AM, Maciek Sokolewicz maciek.sokolew...@gmail.com wrote: Usually if you think you need to use eval: think again. In this case, it again holds true. Instead of doing what you do, you can also reference the variable as: echo ${'image_'.$i}; or echo $GLOBALS['image_'.$i]; Both are preferable by far over using eval, with all its potential security concerns. Oh, man, this is a great list. I didn't even *think* about doing it that way. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable representation
Hi Everyone: I am assigning the value of 4 images to variables following a database query: $image_1 = stripslashes( $row['image_1'] ); $image_2 = stripslashes( $row['image_2'] ); $image_3 = stripslashes( $row['image_3'] ); $image_4 = stripslashes( $row['image_4'] ); What I need help with is how to represent the variable using $i for the number portion in the following WHILE loop. I am not sure of how to correctly do it. I am referring to: $image_{$i} === $i = 1; while ( $i = 4 ) { if ( trim( $image_{$i} ) ) { echo lia href=\http://www.theverseoftheday.info/store-images/; . $image_{$i} . \ title=\Image . $i . \Image . $i . /a/li\r\n; } ++$i; } === How do I substitute $i for the # so I may use a WHILE loop to display the images? (Not all 4 variables have an image.) Ron Piggott www.TheVerseOfTheDay.info
Re: [PHP] Variable representation
It would better to just use an array, and then iterate through that. $images[] = stripslashes( $row['image_1'] ); $images[] = stripslashes( $row['image_2'] ); $images[] = stripslashes( $row['image_3'] ); $images[] = stripslashes( $row['image_4'] ); foreach( $images as $k = $v ) { $k++; // increment k since it starts at 0, instead of 1 if ( strlen( trim( $v ) ) ) { echo lia href=\http://www.theverseoftheday.info/store-images/; . $v . \ title=\Image . $k . \Image . $k . /a/li\r\n; } } Adam. On Sun, Apr 1, 2012 at 8:52 PM, Ron Piggott ron.pigg...@actsministries.orgwrote: Hi Everyone: I am assigning the value of 4 images to variables following a database query: $image_1 = stripslashes( $row['image_1'] ); $image_2 = stripslashes( $row['image_2'] ); $image_3 = stripslashes( $row['image_3'] ); $image_4 = stripslashes( $row['image_4'] ); What I need help with is how to represent the variable using $i for the number portion in the following WHILE loop. I am not sure of how to correctly do it. I am referring to: $image_{$i} === $i = 1; while ( $i = 4 ) { if ( trim( $image_{$i} ) ) { echo lia href=\http://www.theverseoftheday.info/store-images/; . $image_{$i} . \ title=\Image . $i . \Image . $i . /a/li\r\n; } ++$i; } === How do I substitute $i for the # so I may use a WHILE loop to display the images? (Not all 4 variables have an image.) Ron Piggott www.TheVerseOfTheDay.info -- Adam Randall http://www.xaren.net AIM: blitz574 Twitter: @randalla0622 To err is human... to really foul up requires the root password.
Re: [PHP] Variable representation
On 04/02/2012 06:52 AM, Ron Piggott wrote: $image_1 = stripslashes( $row['image_1'] ); $image_2 = stripslashes( $row['image_2'] ); $image_3 = stripslashes( $row['image_3'] ); $image_4 = stripslashes( $row['image_4'] ); [...] (Not all 4 variables have an image.) How is it meant in the database? If it's NULL have a look at this http://goo.gl/89fYv -- RMA. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
On 04/02/2012 07:46 AM, Adam Randall wrote: $images[] = stripslashes( $row['image_1'] ); $images[] = stripslashes( $row['image_2'] ); $images[] = stripslashes( $row['image_3'] ); $images[] = stripslashes( $row['image_4'] ); $images[1] = stripslashes( $row['image_1'] ); $images[2] = stripslashes( $row['image_2'] ); $images[3] = stripslashes( $row['image_3'] ); $images[4] = stripslashes( $row['image_4'] ); would force the order. -- RMA. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
On Sun, Apr 1, 2012 at 10:52 PM, Ron Piggott ron.pigg...@actsministries.org wrote: Hi Everyone: I am assigning the value of 4 images to variables following a database query: $image_1 = stripslashes( $row['image_1'] ); $image_2 = stripslashes( $row['image_2'] ); $image_3 = stripslashes( $row['image_3'] ); $image_4 = stripslashes( $row['image_4'] ); What I need help with is how to represent the variable using $i for the number portion in the following WHILE loop. I am not sure of how to correctly do it. I am referring to: $image_{$i} === $i = 1; while ( $i = 4 ) { if ( trim( $image_{$i} ) ) { echo lia href=\http://www.theverseoftheday.info/store-images/; . $image_{$i} . \ title=\Image . $i . \Image . $i . /a/li\r\n; } ++$i; } === How do I substitute $i for the # so I may use a WHILE loop to display the images? (Not all 4 variables have an image.) Ron Piggott www.TheVerseOfTheDay.info While this doesn't answer your question directly (I will get to it in a moment), you might be better able to use $image as an array and assign the values as: $image[1] = stripslashes( $row['image_1'] ); $image[2] = stripslashes( $row['image_2'] ); $image[3] = stripslashes( $row['image_3'] ); $image[4] = stripslashes( $row['image_4'] ); While noting that arrays in php start indexing at 0, that doens't really matter al that much in your implementation. Assuming you need to set the four image variables separate from the part where you emit the HTML stuff, you can write a loop: foreach (range(1,4) as $i) { $image[$i] = stripslashes($row['image_'.$i]); } which might be slightly less obvious to some, but I think is better code. Then: foreach (range(1,4) as $i) { if (!empty(trim($images[$i]))) { echo lia href=\http://www.theverseoftheday.info/store-images/; . $image[$i] . \ title=\Image . $i . \Image . $i . /a/li\r\n; } } (If you don't need the four images outside of the place you're emitting the HTML, you don't even need to use the intermediate $image[] array, really, and can combing the whole thing in one swell foop: foreach (range(1,4) as $i) { if (!empty($image = trim(stripslashes($row['image_'.$i] { echo lia href=\http://www.theverseoftheday.info/store-images/; . $image . \ title=\Image . $i . \Image . $i . /a/li\r\n; } } And skip the array altogether.) As for doing what you originally asked, that requires doing an eval() on the statement utilizing string interpolation, like so: eval('echo image $i is $image_' . $i . '.PHP_EOL;'); but I think that's a bit harder to read and understand what's going on. When you have to add in escaped quotes and such, it gets much hairier. To utilize it in the loop you have above, I'd split the echoes up: echo lia href=\http://www.theverseoftheday.info/store-images/;; eval ('echo $image_ . $i;'); echo \ title=\Image . $i . \Image . $i . /a/li\r\n; so that the eval portion is doing only what needs to be interpolated and evaled. The rest of the output is fine the way it is. Note that if you did this: echo lia href=\http://www.theverseoftheday.info/store-images/; . eval('echo $image_ . $i;') . \ title=\Image . $i . \Image . $i . /a/li\r\n; the part in the eval would get written out first, then the rest of the echoed string, which is why you would need to split them up first. Generally, I think it's best to completely avoid using eval unless there is no other way to do what you want. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
Ugh, gmail mangled the code there. Here's a pastebin of the response which is better formatted: http://pastie.org/3712761 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable representation
On Mon, Apr 2, 2012 at 12:20 AM, tamouse mailing lists tamouse.li...@gmail.com wrote: Ugh, gmail mangled the code there. Here's a pastebin of the response which is better formatted: http://pastie.org/3712761 Sweet. I spent so long on my reply, two others snuck in before me. :) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable number of arguments problem
I have a function defined thus: function my_func ($arg1, $arg2, $arg3, $arg4, $arg5, $arg6) { // code here } I call this with variously the first three arguments only, or all six, taking care that if I call it with fewer arguments then I don't try to acces $arg4, $arg5, or $arg6 (which is passed by reference, as is $arg1). On my first attempt to execute this, I'm getting: Missing argument 4 for my_func(), called in /path/to/source/file1.php at line 556 and defined in /path/to/source/file2.php at line 3 Is this because $arg6 is passed by reference? There is some reference to this in the docs and the user notes but it's a little unclear. Or is there another reason? Thanks, -- Cheers -- Tim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable number of arguments problem
On 12 Feb 2012, at 18:51, Tim Streater wrote: I have a function defined thus: function my_func ($arg1, $arg2, $arg3, $arg4, $arg5, $arg6) { // code here } I call this with variously the first three arguments only, or all six, taking care that if I call it with fewer arguments then I don't try to acces $arg4, $arg5, or $arg6 (which is passed by reference, as is $arg1). On my first attempt to execute this, I'm getting: Missing argument 4 for my_func(), called in /path/to/source/file1.php at line 556 and defined in /path/to/source/file2.php at line 3 Is this because $arg6 is passed by reference? There is some reference to this in the docs and the user notes but it's a little unclear. Or is there another reason? Optional arguments must be given a default value... function my_func($arg1, $arg2, $arg3, $arg4 = null, $arg5 = null, $arg6 = null) Note that passing a default value by reference was not supported prior to PHP5. All the relevant details are here: http://php.net/functions.arguments -Stuart -- Stuart Dallas 3ft9 Ltd http://3ft9.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: Re: [PHP] Variable number of arguments problem
On 12 Feb 2012 at 19:01, Stuart Dallas stu...@3ft9.com wrote: Optional arguments must be given a default value... function my_func($arg1, $arg2, $arg3, $arg4 = null, $arg5 = null, $arg6 = null) Note that passing a default value by reference was not supported prior to PHP5. All the relevant details are here: http://php.net/functions.arguments Thanks, I do see an example now, although it's not stated explicitly. -- Cheers -- Tim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
On 01/09/2012 07:16 PM, Donovan Brooke wrote: Just to share, a Mr. Harkness forwarded me a consolidated version of my code.. basically substituting the innards for: if (!isset($pmatch) || substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } Cheers, Donovan I would change the above the the following: if ( empty($pmatch) || ( strpos($key, $pmatch) === 0 ) ) { print $key = $valuebr /; } it would be slightly faster -- Jim Lucas http://www.cmsws.com/ http://www.cmsws.com/examples/ http://www.bendsource.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
Jim Lucas wrote: [snip] if (!isset($pmatch) || substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } [snip] I would change the above the the following: if ( empty($pmatch) || ( strpos($key, $pmatch) === 0 ) ) { print $key = $valuebr /; } it would be slightly faster love the skin the cat game! What I like about this Jim is that the strpos() could be changed to allow a contains argument rather than a begins with argument... for example if you wanted to find all variable names containing 'foo'. Something like: if ( empty($pmatch) || (( strpos($tkey, $pmatch) === 0 ) || ( strpos($tkey, $pmatch) 0 ))) { print $key = $valuebr /; } t_foo foo_t t_foo_t would all be found. Thanks! Donovan -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
some pretty natives php functions exists to do the job : But how many times in my life will I have write echo pre; ??? Does anyone have a handy solution? (Make this the default behavior? Add a even more human-readable flag to the function? Create a simple macro in Aptana 3?) Argz, Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
Marc Guay marc.g...@gmail.com wrote: some pretty natives php functions exists to do the job : But how many times in my life will I have write echo pre; ??? Does anyone have a handy solution? (Make this the default behavior? Add a even more human-readable flag to the function? Create a simple macro in Aptana 3?) Argz, Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php I prefer car_dump with the xdebug module installed, the output is nicely formatted, which might be what you're looking for? Thanks, Ash http://ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
Ashley Sheridan a...@ashleysheridan.co.uk wrote: Marc Guay marc.g...@gmail.com wrote: some pretty natives php functions exists to do the job : But how many times in my life will I have write echo pre; ??? Does anyone have a handy solution? (Make this the default behavior? Add a even more human-readable flag to the function? Create a simple macro in Aptana 3?) Argz, Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php I prefer car_dump with the xdebug module installed, the output is nicely formatted, which might be what you're looking for? Thanks, Ash http://ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php That should have been var_dump(), stupid phone auto correct! Thanks, Ash http://ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
On Mon, Jan 09, 2012 at 10:42:59AM -0500, Marc Guay wrote: some pretty natives php functions exists to do the job : But how many times in my life will I have write echo pre; ??? Does anyone have a handy solution? (Make this the default behavior? Add a even more human-readable flag to the function? Create a simple macro in Aptana 3?) I have an init file that I include in every site that contains a few routines I use over and over. One such is: function instrument($legend, $var) { print $legend . br/\n;; print prebr/\n; print_r($var); print /prebr/\n; } I use this routine wherever I want to see what's going on. It formats (particularly) array output so that I can read it, instead of having everything look like JSON, which is much harder to read. Feel free to use the above yourself as needed. Paul -- Paul M. Foster http://noferblatz.com http://quillandmouse.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
Just to share, a Mr. Harkness forwarded me a consolidated version of my code.. basically substituting the innards for: if (!isset($pmatch) || substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } Cheers, Donovan -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable Troubleshooting Code
Hello!, I work in another language mostly and often develop while displaying variables (post,get,and defined) and their values at the bottom of the page or in specific places. So, I thought I'd forward my PHP version as an effort of good Karma to the list perhaps! ;-) Below is 2 simple functions that are helpful for troubleshooting while developing. Just place this code into a .php file and require it at the top of any PHP page. Then, at the bottom of the page, or in a specific (more pertinent) location, call the functions with something like this: ?PHP //troubleshooting code print 'br /bTesting:/bp'; print htmlentities(list_formvars()); print htmlentities(list_vars(get_defined_vars())); print '/p'; ? - Optionally, you can call only specific naming conventions of your variables (if you use them).. ie: print htmlentities(list_vars(get_defined_vars(),'t_')); The above will display all defined vars such as: t_name=value t_city=value t_address=value etc.. Code: --- /* FUNCTION NAME: list_formvars INPUT: optional begins with var OUTPUT: Name = Value br / Name = Value br / USE: For troubleshooting code Example Use: list_formvars(); list_formvars('f_a'); */function list_formvars($pmatch = null) { print br /b'get' Vars:/bbr /; foreach ($_GET as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } print br /b'post' Vars:/bbr /; foreach ($_POST as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } }/* FUNCTION NAME: list_vars INPUT: get_defined_vars(),begins with match OUTPUT: Name = Value br / Name = Value br / USE: For troubleshooting code Example Use: list_vars(get_defined_vars()); list_vars(get_defined_vars(),'t_'); */function list_vars($a_vars,$pmatch = null) { print br /b'defined' Vars:/bbr /; foreach ($a_vars as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } } Cheers, Donovan P.S. Always open to good criticism if you peeps see something that can be written better.. this is about my 3rd PHP project only... so, still heavily learning ;-) -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable Troubleshooting Code
Hi, some pretty natives php functions exists to do the job : var_export — Outputs or returns a parsable string representation of a variable debug_zval_dump — Dumps a string representation of an internal zend value to output var_dump — Dumps information about a variable print_r — Prints human-readable information about a variable echo 'pre'; print_r( array | object ); echo '/pre'; Regards. Le 7 janv. 2012 à 19:00, Donovan Brooke a écrit : Hello!, I work in another language mostly and often develop while displaying variables (post,get,and defined) and their values at the bottom of the page or in specific places. So, I thought I'd forward my PHP version as an effort of good Karma to the list perhaps! ;-) Below is 2 simple functions that are helpful for troubleshooting while developing. Just place this code into a .php file and require it at the top of any PHP page. Then, at the bottom of the page, or in a specific (more pertinent) location, call the functions with something like this: ?PHP //troubleshooting code print 'br /bTesting:/bp'; print htmlentities(list_formvars()); print htmlentities(list_vars(get_defined_vars())); print '/p'; ? - Optionally, you can call only specific naming conventions of your variables (if you use them).. ie: print htmlentities(list_vars(get_defined_vars(),'t_')); The above will display all defined vars such as: t_name=value t_city=value t_address=value etc.. Code: --- /* FUNCTION NAME: list_formvars INPUT: optional begins with var OUTPUT: Name = Value br / Name = Value br / USE: For troubleshooting code Example Use: list_formvars(); list_formvars('f_a'); */function list_formvars($pmatch = null) { print br /b'get' Vars:/bbr /; foreach ($_GET as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } print br /b'post' Vars:/bbr /; foreach ($_POST as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } }/* FUNCTION NAME: list_vars INPUT: get_defined_vars(),begins with match OUTPUT: Name = Value br / Name = Value br / USE: For troubleshooting code Example Use: list_vars(get_defined_vars()); list_vars(get_defined_vars(),'t_'); */function list_vars($a_vars,$pmatch = null) { print br /b'defined' Vars:/bbr /; foreach ($a_vars as $key = $value) { if (isset($pmatch)) { if (substr($key,0,strlen($pmatch)) == $pmatch) { print $key = $valuebr /; } } else { print $key = $valuebr /; } } } Cheers, Donovan P.S. Always open to good criticism if you peeps see something that can be written better.. this is about my 3rd PHP project only... so, still heavily learning ;-) -- D Brooke -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable variable using constant
Hi folks, Let's say that I have 2 constants DEFINE('DESKTOP_URL_en', http://www.website.com/index.php?page=home;); DEFINE('DESKTOP_URL_fr', http://www.website.com/index.php?page=accueil;); and I would like to populate the value of an href with them depending on the user's language. $_SESSION['lang'] is either 'en' or 'fr'. How would I go about referring to this variable? I have tried: ${'DESKTOP_URL_'.$_SESSION['lang']}; ${DESKTOP_URL'.'_'.$_SESSION['lang']}; {DESKTOP_URL'.'_'.$_SESSION['lang']}; etc, to no avail. If it is a regular variable I'm fine, it's the CONSTANT_FORMAT that seems to be causing my brain some issues. Thanks, Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variable using constant
On 10/12/11 11:51, Marc Guay marc.g...@gmail.com wrote: Let's say that I have 2 constants DEFINE('DESKTOP_URL_en', http://www.website.com/index.php?page=home;); DEFINE('DESKTOP_URL_fr', http://www.website.com/index.php?page=accueil;); and I would like to populate the value of an href with them depending on the user's language. $_SESSION['lang'] is either 'en' or 'fr'. How would I go about referring to this variable? Try: $var = constant('DESKTOP_URL_' . $_SESSION['lang']); Regards, Bob -- Robert E. Williams, Jr. Associate Vice President of Software Development Newtek Businesss Services, Inc. -- The Small Business Authority https://www.newtekreferrals.com/rewjr http://www.thesba.com/ Notice: This communication, including attachments, may contain information that is confidential. It constitutes non-public information intended to be conveyed only to the designated recipient(s). If the reader or recipient of this communication is not the intended recipient, an employee or agent of the intended recipient who is responsible for delivering it to the intended recipient, or if you believe that you have received this communication in error, please notify the sender immediately by return e-mail and promptly delete this e-mail, including attachments without reading or saving them in any manner. The unauthorized use, dissemination, distribution, or reproduction of this e-mail, including attachments, is prohibited and may be unlawful. If you have received this email in error, please notify us immediately by e-mail or telephone and delete the e-mail and the attachments (if any). -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variable using constant
$var = constant('DESKTOP_URL_' . $_SESSION['lang']); Very nice, thank you. Marc -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Variable question
-Original Message- From: Ron Piggott [mailto:ron@actsministries.org] Sent: 01 October 2011 18:59 To: php-general@lists.php.net Subject: [PHP] Variable question If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; Just for the record, one more way of doing what you asked for is: echo ${trivia_answer_$correct_answer}; But I totally agree with all the suggestions to use an array instead. Cheers! Mike -- Mike Ford, Electronic Information Developer, Libraries and Learning Innovation, 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] Variable question
If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; $trivia_answer_1 = “1,000”; $trivia_answer_2 = “1,250”; $trivia_answer_3 = “2,500”; $trivia_answer_4 = “5,000”; Ron www.TheVerseOfTheDay.info
Re: [PHP] Variable question
On Oct 1, 2011, at 1:59 PM, Ron Piggott wrote: If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; $trivia_answer_1 = “1,000”; $trivia_answer_2 = “1,250”; $trivia_answer_3 = “2,500”; $trivia_answer_4 = “5,000”; Ron www.TheVerseOfTheDay.info Best bet would to toss this into either an object or array for simplification, otherwise that type of syntax would need the use of eval. example: eval('echo $trivia_answer_'.$correct_answer.';'); best bet would be to.. $trivia_answer = array(); $trivia_answer[1] = 1000; $trivia_answer[2] = 1250; $trivia_answer[3] = 2500; $trivia_answer[4] = 5000; echo $trivia_answer[$correct_answer]; -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable question
On Sat, Oct 1, 2011 at 10:59 AM, Ron Piggott ron@actsministries.orgwrote: If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? You can use variable variables [1] to access the variable by building its name in a string: $name = 'trivia_answer_' . $correct_answer; echo $$name; Peace, David [1] http://php.net/manual/en/language.variables.variable.php
Re: [PHP] Variable question
On 11-10-01 02:03 PM, Mike Mackintosh wrote: On Oct 1, 2011, at 1:59 PM, Ron Piggott wrote: If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; $trivia_answer_1 = “1,000”; $trivia_answer_2 = “1,250”; $trivia_answer_3 = “2,500”; $trivia_answer_4 = “5,000”; Ron www.TheVerseOfTheDay.info Best bet would to toss this into either an object or array for simplification, otherwise that type of syntax would need the use of eval. example: eval('echo $trivia_answer_'.$correct_answer.';'); best bet would be to.. $trivia_answer = array(); $trivia_answer[1] = 1000; $trivia_answer[2] = 1250; $trivia_answer[3] = 2500; $trivia_answer[4] = 5000; echo $trivia_answer[$correct_answer]; Agreed the OP's value list isn't optimal, but eval is not needed to address the solution: ?php $trivia_answer_1 = 1,000; $trivia_answer_2 = 1,250; $trivia_answer_3 = 2,500; $trivia_answer_4 = 5,000; $answer = isset( ${'trivia_answer_'.$correct_answer} ) ? ${'trivia_answer_'.$correct_answer} : 'Not found'; echo $answer.\n; ? 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] Variable question
On 01 Oct 2011 at 18:59, Ron Piggott ron@actsministries.org wrote: If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; $trivia_answer_1 = “1,000”; $trivia_answer_2 = “1,250”; $trivia_answer_3 = “2,500”; $trivia_answer_4 = “5,000”; Not completely obvious to me what you're trying to do but I assume its: echo '\$trivia_answer_' . $correct_answer . = \ . $somevalue . \;; -- Cheers -- Tim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable question
On Sat, 1 Oct 2011, Mike Mackintosh wrote: Best bet would to toss this into either an object or array for simplification, otherwise that type of syntax would need the use of eval. example: eval('echo $trivia_answer_'.$correct_answer.';'); You could do: $var = trivia_answer_.$correct_answer; echo $$var; But I agree that an array would be simpler. best bet would be to.. $trivia_answer = array(); $trivia_answer[1] = 1000; $trivia_answer[2] = 1250; $trivia_answer[3] = 2500; $trivia_answer[4] = 5000; echo $trivia_answer[$correct_answer]; You can define this a bit more simply: $trivia_answer = array ( 1 = 1000, 2 = 1250, 3 = 2500, 4 = 5000 ); You can do it even more simply by just giving the values, but indexes wil start at 0: ?php $trivia_answer = array (1000, 1250, 2500, 5000); print_r ($trivia_answer); ? Array ( [0] = 1000 [1] = 1250 [2] = 2500 [3] = 5000 ) While manually defining an array like this is only slightly less tedius than using 4 numbered variables, it's a lot easier to do if you're getting data from somewhere else (e.g. a database of trivia questions). To use the original way proposed, you'd have to keep constructing variable names, which arrays avoid quite nicely. In my opinion, the only real usefulness for a syntax like $$var (above) is if you want to do something with a bunch of variables in one go. For example: foreach (array (title, artist, album, label) as $field) echo ucwords($field) . ': ' . $$field . 'BR'; The above comes from a function which manages only a single record, so no real need to use an array. I could of course, e.g. record['title'] etc, but I don't see much could be gained unless I needed to be able to manage an entire record as a single unit. Geoff. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable scope
Can anyone explain this to me. function sendEmail($uname,$subjField,$firstname,$lastname,$email, $reply,$e_cc,$e_bcc,$comments,$ip,$Date,$time){ $uname = trim($uname); $subjField = trim($subjField); $firstname = trim($firstname); $lastname = trim($lastname); $email = trim($email); $reply = trim($reply); $e_cc = trim($e_cc); $e_bcc = trim($e_bcc); $comments = trim($comments); $ip = trim($ip); $Date = trim($Date); $time = trim($time); //If I trace here email, reply and the CCs are ok if(($firstname strlen($firstname = trim($firstname)) 2) ($lastname strlen($lastname = trim($lastname)) 2)) { $fullname = $firstname. .$lastname; } else { $fullname = Member; } $fullname = trim($fullname); $To = ; $from = ; $headerTXT = ; $bounce_email = CO_NAME. .BOUNCE_ADDR.; $subject = $subjectField; $bulk = false; //What kind of email is being sent //Email exists, no Cc or Bcc if(!empty($email) empty($_email_cc) empty($_email_bcc)) { $To = $fullname. .$email.; $from = Member .$reply.; $headerTXT = New message from .CO_NAME. member .$uname; $bulk = false; } //Email empty, Cc exists no Bcc else if(empty($email) !empty($e_cc) empty($e_bcc)) { $To = $bounce_email; $from = Member .$reply.; $headerTXT = New message from .CO_NAME. member .$uname; $bulk = true; } ... //If I trace here $To, $from have everything except the (anything between), so for instance.. $To = John Doe ; $from = Member ; not $To = John Doe j...@email.com ; $from = Member mem...@company.com; So $email and $reply are loosing their value/scope But the .CO_NAME. and .BOUNCE_ADDR. are working!?!? This is also in a page with many other email functions just like this one and they work. Only difference is the $To and $from are not inside an if() { statement. How did my variables loose scope??? One other note, if I put.. $To = htmlspecialchars($fullname. .$email.); then $To is correct when I trace.. $To = John Doe j...@email.com ; but it wont send because the smtp mail will not send to $To = John Doe lt;j...@email.comgt; I MUST be doing something wrong. Also, I did read about using Name em...@email.com but the other email functions work fine with those, so I'm not sure what's going on. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com
Re: [PHP] Variable scope
On Jul 14, 2011, at 3:54 PM, Karl DeSaulniers wrote: Can anyone explain this to me. function sendEmail($uname,$subjField,$firstname,$lastname,$email, $reply,$e_cc,$e_bcc,$comments,$ip,$Date,$time){ $uname = trim($uname); $subjField = trim($subjField); $firstname = trim($firstname); $lastname = trim($lastname); $email = trim($email); $reply = trim($reply); $e_cc = trim($e_cc); $e_bcc = trim($e_bcc); $comments = trim($comments); $ip = trim($ip); $Date = trim($Date); $time = trim($time); //If I trace here email, reply and the CCs are ok if(($firstname strlen($firstname = trim($firstname)) 2) ($lastname strlen($lastname = trim($lastname)) 2)) { $fullname = $firstname. .$lastname; } else { $fullname = Member; } $fullname = trim($fullname); $To = ; $from = ; $headerTXT = ; $bounce_email = CO_NAME. .BOUNCE_ADDR.; $subject = $subjectField; $bulk = false; //What kind of email is being sent //Email exists, no Cc or Bcc if(!empty($email) empty($_email_cc) empty($_email_bcc)) { $To = $fullname. .$email.; $from = Member .$reply.; $headerTXT = New message from .CO_NAME. member .$uname; $bulk = false; } //Email empty, Cc exists no Bcc else if(empty($email) !empty($e_cc) empty($e_bcc)) { $To = $bounce_email; $from = Member .$reply.; $headerTXT = New message from .CO_NAME. member .$uname; $bulk = true; } ... //If I trace here $To, $from have everything except the (anything between), so for instance.. $To = John Doe ; $from = Member ; Have you looked at the output in the page source? The may be getting eaten by the browser. You may want to use htmlentities on your trace output (but not the actual variables). not $To = John Doe j...@email.com ; $from = Member mem...@company.com; So $email and $reply are loosing their value/scope But the .CO_NAME. and .BOUNCE_ADDR. are working!?!? I assume these are defined constants, which don't have scope (or, perhaps more accurately, always have global scope). This is also in a page with many other email functions just like this one and they work. Only difference is the $To and $from are not inside an if() { statement. How did my variables loose scope??? One other note, if I put.. $To = htmlspecialchars($fullname. .$email.); then $To is correct when I trace.. $To = John Doe j...@email.com ; but it wont send because the smtp mail will not send to $To = John Doe lt;j...@email.comgt; I MUST be doing something wrong. Also, I did read about using Name em...@email.com but the other email functions work fine with those, so I'm not sure what's going on. TIA, Best, Karl DeSaulniers Design Drumm http://designdrumm.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable (Class instantiation) collision
I am running into a variable collision. The project I'm developing is NOT guaranteed to be operating on PHP5. Any solution I find should (hopefully) be able to run on PHP4 (yes, I know PHP4 is deprecated). I am building a bridge between two third-party applications. Both instantiate their respective database class assigning it to $db and I cannot change that. So, I am interested in solutions to this. I found a reference to a Packager class and will be looking at it shortly. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable (Class instantiation) collision
Just to clarify, both packages are instantiating and calling their respective database classes from the $db var, which is in the global scope. Is this correct? This is why I hate the global scope, I hate it, I hate it! On Tue, Oct 5, 2010 at 3:47 PM, Brian Smither bhsmit...@gmail.com wrote: I am running into a variable collision. The project I'm developing is NOT guaranteed to be operating on PHP5. Any solution I find should (hopefully) be able to run on PHP4 (yes, I know PHP4 is deprecated). I am building a bridge between two third-party applications. Both instantiate their respective database class assigning it to $db and I cannot change that. So, I am interested in solutions to this. I found a reference to a Packager class and will be looking at it shortly. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable (Class instantiation) collision
Just to clarify, both packages are instantiating and calling their respective classes from the $db var, which is in the global scope. Is this correct? I would say yes to the way you are asking. Take the following two applications. The four respective statements are in each their respective script. Application A: ?php class foo {} $db = new foo(); $outA = barA(); function barA() { global $db; include(Application B); } ? Application B: ?php class bar {} $db = new bar(); $outB = barB(); function barB() { global $db; } ? The bridge project is operating in A and include()'ing the script that is B (as I have not found an API for B). $db in B is colliding with $db in A. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable (Class instantiation) collision
Short of refactoring ApplicationB, can you set it up as a SOAP/REST service that AppA calls? On Tue, Oct 5, 2010 at 5:02 PM, Brian Smither bhsmit...@gmail.com wrote: Just to clarify, both packages are instantiating and calling their respective classes from the $db var, which is in the global scope. Is this correct? I would say yes to the way you are asking. Take the following two applications. The four respective statements are in each their respective script. Application A: ?php class foo {} $db = new foo(); $outA = barA(); function barA() { global $db; include(Application B); } ? Application B: ?php class bar {} $db = new bar(); $outB = barB(); function barB() { global $db; } ? The bridge project is operating in A and include()'ing the script that is B (as I have not found an API for B). $db in B is colliding with $db in A. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable (Class instantiation) collision
If you have total control over application A which contains the bridge code, the easiest is to change it to use a different global variable, $dbA. This must not be doable or you wouldn't have asked. If you have control over the bridge code, and it alone calls A and B, then you could swap the $db variables between calls: $db = null; $dbA = null; $dbB = null; function copyPersons() { useA(); $persons = loadPersonsFromA(); useB(); savePersonsInB($persons); } function connect() { global $db, $dbA, $dbB; connectToA(); $dbA = $db; unset($db); connectToB(); $dbB = $db; unset($db); } function useA() { global $db, $dbA; $db = $dbA; } function useB() { global $db, $dbB; $db = $dbB; } This is the simplest implementation. You could get trickier by tracking which system is in use and only swapping them as-needed, writing a facade around the APIs to A and B. It's ugly, but it works. David
Re: [PHP] Variable in variable.
On 10-08-26 09:54 AM, João Cândido de Souza Neto wrote: I know that in PHP I can use this: $var1 = text; $var2 = '$var1'; 4cho $$var2; So it gives me text. It would if you didn't have typos and the wrong quotes in the above :) My question is, is there a way of doing it with constant like this? define(CONST, text); $test = CONST; echo $$test; So it gives me text. http://ca3.php.net/manual/en/function.constant.php 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] Variable in variable.
Really cool... Thanks and fogive me by my mistake. hehe -- João Cândido de Souza Neto Robert Cummings rob...@interjinn.com escreveu na mensagem news:4c76743a.2060...@interjinn.com... On 10-08-26 09:54 AM, João Cândido de Souza Neto wrote: I know that in PHP I can use this: $var1 = text; $var2 = '$var1'; 4cho $$var2; So it gives me text. It would if you didn't have typos and the wrong quotes in the above :) My question is, is there a way of doing it with constant like this? define(CONST, text); $test = CONST; echo $$test; So it gives me text. http://ca3.php.net/manual/en/function.constant.php 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] Variable variables into an array.
On 10 August 2010 18:08, Andrew Ballard aball...@gmail.com wrote: On Tue, Aug 10, 2010 at 12:23 PM, Richard Quadling rquadl...@gmail.com wrote: On 10 August 2010 16:49, Jim Lucas li...@cmsws.com wrote: Richard Quadling wrote: Hi. Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? The output is an empty array. Examining $GLOBALS, I end up with an entries ... [Set] = Array ( ) [Entry] = Set[1] [Value] = Assigned [Set[1]] = Assigned According to http://docs.php.net/manual/en/language.variables.basics.php, a variable named Set[1] is not a valid variable name. The [ and ] are not part of the set of valid characters. In testing all the working V4 and V5 releases I have, the output is always an empty array, so it looks like it is me, but the invalid variable name is an issue I think. Regards, Richard. NOTE: The above is a simple test. I'm trying to map in nested data to over 10 levels. For something like this, a string that looks like a nested array reference, you might need to involve eval for it to derive that nested array. I'm happy with that. It seems variable variables can produce variables that do not follow the same naming limitations as normal variables. It would seem so. If eval() works, can you rearrange the strings a little to make use of parse_str() and avoid the use of eval()? Andrew php -r parse_str('a[1][2][3]=richard quadling'); var_dump($a); outputs ... array(1) { [1]= array(1) { [2]= array(1) { [3]= string(16) richard quadling } } } Perfect. Thanks. -- Richard Quadling. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Variable variables into an array.
From: Richard Quadling Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; ^^ Shouldn't that be $Set[1]? $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? Bob McConnell -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variables into an array.
On 11 August 2010 13:58, Bob McConnell r...@cbord.com wrote: From: Richard Quadling Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; ^^ Shouldn't that be $Set[1]? $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? Bob McConnell No. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable variables into an array.
Hi. Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? The output is an empty array. Examining $GLOBALS, I end up with an entries ... [Set] = Array ( ) [Entry] = Set[1] [Value] = Assigned [Set[1]] = Assigned According to http://docs.php.net/manual/en/language.variables.basics.php, a variable named Set[1] is not a valid variable name. The [ and ] are not part of the set of valid characters. In testing all the working V4 and V5 releases I have, the output is always an empty array, so it looks like it is me, but the invalid variable name is an issue I think. Regards, Richard. NOTE: The above is a simple test. I'm trying to map in nested data to over 10 levels. -- Richard Quadling. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variables into an array.
Richard Quadling wrote: Hi. Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? The output is an empty array. Examining $GLOBALS, I end up with an entries ... [Set] = Array ( ) [Entry] = Set[1] [Value] = Assigned [Set[1]] = Assigned According to http://docs.php.net/manual/en/language.variables.basics.php, a variable named Set[1] is not a valid variable name. The [ and ] are not part of the set of valid characters. In testing all the working V4 and V5 releases I have, the output is always an empty array, so it looks like it is me, but the invalid variable name is an issue I think. Regards, Richard. NOTE: The above is a simple test. I'm trying to map in nested data to over 10 levels. For something like this, a string that looks like a nested array reference, you might need to involve eval for it to derive that nested array. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variables into an array.
On 10 August 2010 16:49, Jim Lucas li...@cmsws.com wrote: Richard Quadling wrote: Hi. Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? The output is an empty array. Examining $GLOBALS, I end up with an entries ... [Set] = Array ( ) [Entry] = Set[1] [Value] = Assigned [Set[1]] = Assigned According to http://docs.php.net/manual/en/language.variables.basics.php, a variable named Set[1] is not a valid variable name. The [ and ] are not part of the set of valid characters. In testing all the working V4 and V5 releases I have, the output is always an empty array, so it looks like it is me, but the invalid variable name is an issue I think. Regards, Richard. NOTE: The above is a simple test. I'm trying to map in nested data to over 10 levels. For something like this, a string that looks like a nested array reference, you might need to involve eval for it to derive that nested array. I'm happy with that. It seems variable variables can produce variables that do not follow the same naming limitations as normal variables. -- Richard Quadling. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable variables into an array.
On Tue, Aug 10, 2010 at 12:23 PM, Richard Quadling rquadl...@gmail.com wrote: On 10 August 2010 16:49, Jim Lucas li...@cmsws.com wrote: Richard Quadling wrote: Hi. Quick set of eyes needed to see what I've done wrong... The following is a reduced example ... ?php $Set = array(); $Entry = 'Set[1]'; $Value = 'Assigned'; $$Entry = $Value; print_r($Set); ? The output is an empty array. Examining $GLOBALS, I end up with an entries ... [Set] = Array ( ) [Entry] = Set[1] [Value] = Assigned [Set[1]] = Assigned According to http://docs.php.net/manual/en/language.variables.basics.php, a variable named Set[1] is not a valid variable name. The [ and ] are not part of the set of valid characters. In testing all the working V4 and V5 releases I have, the output is always an empty array, so it looks like it is me, but the invalid variable name is an issue I think. Regards, Richard. NOTE: The above is a simple test. I'm trying to map in nested data to over 10 levels. For something like this, a string that looks like a nested array reference, you might need to involve eval for it to derive that nested array. I'm happy with that. It seems variable variables can produce variables that do not follow the same naming limitations as normal variables. It would seem so. If eval() works, can you rearrange the strings a little to make use of parse_str() and avoid the use of eval()? Andrew -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Variable name as a variable?
I need to store a variable name as a variable. Note quite a C-style pointer, but a way to access one variable who's name is stored in another variable. As part of a spam-control measure, a certain public-facing form will have dummy rotating text fields and a hidden field that will describe which text field should be considered, like this: input type=text name=text_1 input type=text name=text_2 input type=text name=text_3 input type=hidden name=real_field value=text_2 As this will be a very general-purpose tool, a switch statement on the hidden field's value would not be appropriate here. Naturally, the situation will be much more complex and this is a non-obfuscated generalization of the HTML side of things which should describe the problem that I need to solve on the server side. Thanks in advance for any ideas. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable name as a variable?
On Mon, 2009-10-05 at 16:56 +0200, Dotan Cohen wrote: I need to store a variable name as a variable. Note quite a C-style pointer, but a way to access one variable who's name is stored in another variable. As part of a spam-control measure, a certain public-facing form will have dummy rotating text fields and a hidden field that will describe which text field should be considered, like this: input type=text name=text_1 input type=text name=text_2 input type=text name=text_3 input type=hidden name=real_field value=text_2 As this will be a very general-purpose tool, a switch statement on the hidden field's value would not be appropriate here. Naturally, the situation will be much more complex and this is a non-obfuscated generalization of the HTML side of things which should describe the problem that I need to solve on the server side. Thanks in advance for any ideas. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il What's wrong with this: $user_value = $_REQUEST[$_REQUEST['real_field']]; Obviously this isn't production worthy code, you'd really need to put the whole thing in a ternary if to check if the values actually exist, but this would definitely solve your problem. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Variable name as a variable?
- Original Message From: Dotan Cohen dotanco...@gmail.com To: php-general. php-general@lists.php.net Sent: Mon, October 5, 2009 7:56:48 AM Subject: [PHP] Variable name as a variable? I need to store a variable name as a variable. Note quite a C-style pointer, but a way to access one variable who's name is stored in another variable. As part of a spam-control measure, a certain public-facing form will have dummy rotating text fields and a hidden field that will describe which text field should be considered, like this: input type=text name=text_1 input type=text name=text_2 input type=text name=text_3 input type=hidden name=real_field value=text_2 As this will be a very general-purpose tool, a switch statement on the hidden field's value would not be appropriate here. Naturally, the situation will be much more complex and this is a non-obfuscated generalization of the HTML side of things which should describe the problem that I need to solve on the server side. Thanks in advance for any ideas. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php You mean something like this? $var_name = text_2; echo $$var_name; // equivalent to echo $text_2; Regards, Tommy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Variable name as a variable?
On Mon, 5 Oct 2009 16:56:48 +0200 Dotan Cohen dotanco...@gmail.com wrote: I need to store a variable name as a variable. Note quite a C-style pointer, but a way to access one variable who's name is stored in another variable. As part of a spam-control measure, a certain public-facing form will have dummy rotating text fields and a hidden field that will describe which text field should be considered, like this: input type=text name=text_1 input type=text name=text_2 input type=text name=text_3 input type=hidden name=real_field value=text_2 As this will be a very general-purpose tool, a switch statement on the hidden field's value would not be appropriate here. Naturally, the situation will be much more complex and this is a non-obfuscated generalization of the HTML side of things which should describe the problem that I need to solve on the server side. Thanks in advance for any ideas. Some reading on this if you're interested: http://us2.php.net/manual/en/language.variables.variable.php You can also access array properties using variables if you like: $foo-some_prop = 'Hi there!'; $bar = 'some_prop'; echo $foo-$bar; Regards, Torben -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php