PHP function to add data to string
Though using global variables within functions is considered harmful.
$myText = ""; function addText($textString) < global $myText; $myText .= $textString; >addText("Hello there. "); echo $myText;
the reason you have to do the is is bc $myText is not in the scope on the function.
so to put it in scope, you have to tell the function which global variables to use
Ok let me actually help you as opposed to just telling you how to get your current example to work. Basically, variables defined outside a custom function are not visible inside it. In your example your function has no idea what $myText is because it was declared out side of the functions scope. To pass variables to a function you will need to add them as parameters — the variables you pass with a function when you define and then when you call it, eg: function addText($param1, $param2) .
As other have mentioned, you can allow functions to see certain variables by using the global keyword, but only really use this for abstract things like database connections, not the actually data you want to configure, do all that inside your function.
Hopefully this will help you understand PHP a bit more.
This is what you call variable scope. That’s the part of the code where your variable is known as explained here. To make a short story even shorter, even though your $myText inside the function shares the name with the one outside, they’re completely different. They’re different boxes, one in your room (the one inside your function) and one outside (the other one). Even if they’re labeled the same, things you put into one of them wouldn’t show up inside the other one as well. There are two ways to do what you want to do.
First the easy but bad way: Make one big all including box by adding the global keyword to the one inside the function like posted before. This is like saying «Look outside for a box with this label and use this one.» But remember: Global variables are BAD.
Tempting as the dark side may be there is an other way. Taking your box with you.
$myText = ""; function addText($existingText, $textToAdd) < return $existingText . $textToAdd; >addText($myText, "Look, it's there!"); echo $myText;
May the source be with you.
strval
Get the string value of a variable. See the documentation on string for more information on converting to string.
This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format() .
Parameters
The variable that is being converted to a string .
value may be any scalar type, null , or an object that implements the __toString() method. You cannot use strval() on arrays or on objects that do not implement the __toString() method.
Return Values
The string value of value .
Examples
Example #1 strval() example using PHP magic __toString() method.
class StrValTest
public function __toString ()
return __CLASS__ ;
>
>
?php
// Prints ‘StrValTest’
echo strval (new StrValTest );
?>
See Also
- boolval() — Get the boolean value of a variable
- floatval() — Get float value of a variable
- intval() — Get the integer value of a variable
- settype() — Set the type of a variable
- sprintf() — Return a formatted string
- number_format() — Format a number with grouped thousands
- Type juggling
- __toString()
User Contributed Notes 9 notes
As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.
Some notes about how this function has changed over time, with regards the following statement:
> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.
In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.
From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».
For objects that do not implement __toString(), the behaviour has varied:
PHP 4: «Object»
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error: Object of class X could not be converted to string
If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here’s a function to do it.
Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]
I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.
The function returns ‘#’ if the argument does not represent a whole number.
$nwords = array( «zero» , «one» , «two» , «three» , «four» , «five» , «six» , «seven» ,
«eight» , «nine» , «ten» , «eleven» , «twelve» , «thirteen» ,
«fourteen» , «fifteen» , «sixteen» , «seventeen» , «eighteen» ,
«nineteen» , «twenty» , 30 => «thirty» , 40 => «forty» ,
50 => «fifty» , 60 => «sixty» , 70 => «seventy» , 80 => «eighty» ,
90 => «ninety» );
function int_to_words ( $x ) global $nwords ;
if(! is_numeric ( $x ))
$w = ‘#’ ;
else if( fmod ( $x , 1 ) != 0 )
$w = ‘#’ ;
else if( $x < 0 ) $w = 'minus ' ;
$x = — $x ;
> else
$w = » ;
// . now $x is a non-negative integer.
if( $x < 21 ) // 0 to 20
$w .= $nwords [ $x ];
else if( $x < 100 ) < // 21 to 99
$w .= $nwords [ 10 * floor ( $x / 10 )];
$r = fmod ( $x , 10 );
if( $r > 0 )
$w .= ‘-‘ . $nwords [ $r ];
> else if( $x < 1000 ) < // 100 to 999
$w .= $nwords [ floor ( $x / 100 )] . ‘ hundred’ ;
$r = fmod ( $x , 100 );
if( $r > 0 )
$w .= ‘ and ‘ . int_to_words ( $r );
> else if( $x < 1000000 ) < // 1000 to 999999
$w .= int_to_words ( floor ( $x / 1000 )) . ‘ thousand’ ;
$r = fmod ( $x , 1000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$w .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
> else < // millions
$w .= int_to_words ( floor ( $x / 1000000 )) . ‘ million’ ;
$r = fmod ( $x , 1000000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$word .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
>
>
return $w ;
>
?>
Usage:
echo ‘There are currently ‘ . int_to_words ( $count ) . ‘ members logged on.’ ;
?>
I can’t help being surprised that
evaluates to true. It’s the same with strval and single quotes.
=== avoids it.
Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).
// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015
// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).
2326201276 — (-1968766020) = 4294967296.
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:
/**
* Returns the string value of a variable
*
* This differs from strval in that it invokes __toString if an object is given
* and the object has that method
*/
function stringVal ($value)
// We use get_class_methods instead of method_exists to ensure that __toString is a public method
if (is_object($value) && in_array(«__toString», get_class_methods($value)))
return strval($value->__toString());
else
return strval($value);
>
In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )
function int_to_words($x) global $nwords;
if(!is_numeric($x))
$w = ‘#’;
else if(fmod($x, 1) != 0)
$w = ‘#’;
else if($x < 0) $w = $nwords['minus'].' ';
$x = -$x;
> else
$w = »;
// . now $x is a non-negative integer.
if($x < 21) // 0 to 20
$w .= $nwords[$x];
else if($x < 100) < // 21 to 99
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
$w .= ‘-‘. $nwords[$r];
> else if($x < 1000) < // 100 to 999
$w .= $nwords[floor($x/100)] .’ ‘.$nwords[‘hundred’];
$r = fmod($x, 100);
if($r > 0)
$w .= ‘ ‘.$nwords[‘separator’].’ ‘. int_to_words($r);
> else if($x < 1000000) < // 1000 to 999999
$w .= int_to_words(floor($x/1000)) .’ ‘.$nwords[‘thousand’];
$r = fmod($x, 1000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$w .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);
>
> else < // millions
$w .= int_to_words(floor($x/1000000)) .’ ‘.$nwords[‘million’];
$r = fmod($x, 1000000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$word .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);
>
>
>
return $w;
>
// Usage in English
$nwords = array( «zero», «one», «two», «three», «four», «five», «six», «seven»,
«eight», «nine», «ten», «eleven», «twelve», «thirteen»,
«fourteen», «fifteen», «sixteen», «seventeen», «eighteen»,
«nineteen», «twenty», 30 => «thirty», 40 => «forty»,
50 => «fifty», 60 => «sixty», 70 => «seventy», 80 => «eighty»,
90 => «ninety» , «hundred» => «hundred», «thousand»=> «thousand», «million»=>»million»,
«separator»=>»and», «minus»=>»minus»);
echo ‘There are currently ‘. int_to_words(-120223456) . ‘ members logged on.
‘;
//Utilisation en Francais
$nwords = array( «zéro», «un», «deux», «trois», «quatre», «cinq», «six», «sept»,
«huit», «neuf», «dix», «onze», «douze», «treize»,
«quatorze», «quinze», «seize», «dix-sept», «dix-huit»,
«dix-neuf», «vingt», 30 => «trente», 40 => «quarante»,
50 => «cinquante», 60 => «soixante», 70 => «soixante-dix», 80 => «quatre-vingt»,
90 => «quatre-vingt-dix» , «hundred» => «cent», «thousand»=> «mille», «million»=>»million»,
«separator»=>»», «minus»=>»moins»);
echo ‘Il y a actuellement ‘. int_to_words(-120223456) . ‘ membres connectés.
‘;
named binding of variables in strings?
I’m looking for function like sprintf(), except whereas with sprintf() you bind the values by order of arguments, I want something where I can bind variables by name. So, if I had the string «Hello $name! We’re please to have you visit, $name!» , you could pass an array or something and get the resultant string from it. Something like the PDO statements, but just for plain strings, not database queries. What can I use?
3 Answers 3
preg_replace/e or preg_replace_callback is your best bet
$vars = array('name' => 'Joe', 'age' => 25); $str = "@name is @age years old"; echo preg_replace('/@(\w+)/e', '$vars["$1"]', $str);
PHP has built in support for evaluating variables inside of double-quoted strings. While you can’t «pass-in» an array to it, you could think of the current variable scope as the input for the string builder «function».
$name = "Kendall Hopkins"; print "Hello !"; //Hello Kendall Hopkins!
A more flexible solution might be to abstract out the code into a closure. This doesn’t depend on eval and will probably run faster.
$hello_two = function ( array $params ) < extract( $params ); return "Hello $name1 and $name2!"; >//Hello User and Kendall $hello_two( array( "var1" => "User", "var2" => "Kendall" ) );
Yes, I know, but I want a function that does this so I can re-use my template string in several places. In other words I don’t want the variables bound at the time of writing. Using this php functionality makes the string a one-off and I can’t re-use that.
@Gian Yes, each string needs to be compiled into opcode before the PHP is run in order to gain decent performance. Closures provide a portable way of «moving» around PHP string building construct. Anything that’s eval’ed requires the PHP compiler to read it EACH time the code is run, regardless of how many times it’s run.
That wasn’t what I was asking. I’m suggesting that you have to write a new function for every different format string you may wish to use. That seems a little brittle. I agree eval is not a great solution, but I’m trying to think if there is some better way that is general (i.e. parameterised in terms of the format string and the data value array).
Perhaps you could use anonymous functions, such that the free variables are bound as parameters in the anonymous function, which returns a string with the values populating the free variables. This would work well in conjunction with the extract function inside a closure, wherein the keys from your array become real variables within a local scope necessary to evaluate the variables referenced in the format string.
Or there is probably a relatively simple version using eval (this is just an illustration, not tested code):
function named_printf ($format_string, $values) < extract($values); $result = $format_string; eval('$result = "'.$format_string.'";'); return $result; >echo named_printf ('Hello $msg', array('msg'=>'World'));
PHP’s scope control mechanisms are a bit scary, so you may want to verify that this isn’t going to leak variables into scope all over the place. It’d also be worth santising input.