Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

valid variable names

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I was wondering how to make these variable names valid for php4. I am having problems when there is a '&' or a '.' in the variable name. Could anything be done to make this work?

example:
$m&m
$U.S.A.
 
You can't use those variable names.

From the PHP online manual:
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Actually, that's not expressly true. If you wanted to, I suppose you reengineer the Zend engine by editing the source code. ______________________________________________________________________
Did you know?
The quality of our answers is directly proportional to the number of stars you vote?
 
The problem with what you want to do is that both & and . are operators in PHP.
 
I suppose you have your reasons for doing this, somewhere. I would say it's most likely because you haven't abstracted your operations enough.

But, If you really need to be able to somehow represent variables that have odd names, you might think about character encoding. The following example looks a little complex at first, but what it does is use the ord() and chr() functions respectively. ord() will take any character and return its ASCII number. chr() will simply do the reverse. Also, we take advantage of the "variable variable" concept (see $$newname), and the fact that any variable name can start with an underscore (_):

Code:
<?php

//How to encode strings as character sets

$varname = &quot;m&m&quot;;

for($i=0 ;$i < strlen($varname) ; $i++)
{
  $newname .= '_';
  $newname .= ord($varname{$i});
}

echo &quot;new varname is \$&quot; . $newname . &quot;<br><br>&quot;;
$$newname = &quot;The value of our oddly-named variable&quot;;
echo &quot;\$$newname = &quot; . $$newname . &quot;<br><br>&quot;;

$oldname_arr = explode('_', $newname);
foreach($oldname_arr as $key=>$value)
{
  $oldname .= chr($value);
}

echo &quot;Reconstructed old name is &quot; . $oldname;

?>

This kind of method can allow you to have lists of names, (such as form a database), which can be read as string variables, and then turned into variables of their own. It's a heavy level of abstraction, but it can be useful in some cases. -------------------------------------------

&quot;Now, this might cause some discomfort...&quot;
(
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top