Changing built-in PHP variable to a local variable

$numericServerName=str_replace('.','', $_SERVER[SERVER_NAME]);
if (is_numeric($numericServerName)) {
echo $_SERVER[SERVER_NAME].' is an IP.';
} else {
echo $_SERVER[-SERVER_NAME].' is a domain.';

The code above and the code below produce a same browsing result.

The code above calls “$_SERVER[SERVER_NAME]” 3 times.

The code below calls $_SERVER[SERVER_NAME]" 1 time because it changes “$_SERVER[SERVER_NAME]” to a local variable “$serverName”
Which one is better practice?
(I bet the code below is better, but I am not sure)


$numericServerName=str_replace('.','', $serverName);

if (is_numeric($numericServerName)) {
echo $serverName.' is an IP.';
} else {
echo $serverName.' is a domain.';

I think you’ll find that there should be quotes round SERVER_NAME.

You’re not calling anything, you are accessing an array element. Assigning a local variable to a global array element might seem like a good idea but there’s not a lot of point in it.

It seems like it is better to assign it to a local variable (it’s less typing, for one thing), but one disadvantage is that you can’t tell easily what is in $serverName. You can be pretty sure of what is in $_SERVER['SERVER_NAME'] any time it is referenced in your code.

The name of the local variable “serverName” is intuitive.
I can easily think of “$_SERVER[‘SERVER_NAME’]” with the word “serveName”.

Is there any other advantage except less typing, especially in performance? .

Of course it is, right now, you just wrote it. What about in a week, is it still intuitive then? What about a year?

So you recommend 3 times of using “$_SERVER[‘SERVER_NAME’]” rather than assigning a local variable.

The readability is, I also think, the most important, especially after a year.
Thank you.

Is $_SERVER[SERVER_NAME] an array element?

if so, Is $_SERVER[REMOTE_ADDR] or $_SERVER[HTTP_USER_AGENT] also an array element?

// Array
$array = $_SERVER;
echo '<br>count($array) ==> ' ,count($array);

foreach( $array as $key => $element) :
   echo '<br>#$key : ' .$key .' ==> ' . $element;

// OR

echo '<pre>'; // add line feeds
echo '</pre>';

Tapped on a tablet and not tried.

Edited on a desktop:

Changed $id to $key in accordance with PHP’s Online Manual:

Arrays are:

  1. tremendously powerful
  2. ideal for grouping various kinds of data
  3. data need not be all the same type
  4. can have sub-arrays
  5. saves a lot of typing
  6. easily transferred
  7. checkout some useful PHP array functions
  8. you need to start thinking arrays and sorting, searching, pushing, popping, filling, flipping, etc
$table  = '<table>';
$table .=  '<tr><th> $key </th><th> $element </th></tr>';
  foreach( $array as $key => $element) :
     $table .=  '<tr><td>' .$key  .'</td><td>'  .$element .'</td></tr>';
$table .= '</table>';

echo $table; 

Sticking strictly to your question, “Which one is better practice”, the better practice is to NEVER create variables for nothing. In your code example you have not done any kind of transformation to the original value whatsoever so creating a new variable for it is completely pointless and redundant.

Yes, the manual is your friend.

Also, broadening the scope a little bit…

This functionality already exists in PHP:
filter_var will return False if the filter fails, otherwise it will return the IP.


@joon1 So far as performance goes, I think you are prematurely optimizing. It’s better for the code to be more maintainable and readable. So whatever is maintainable and readable for your software project is best - just my opinion.

But for argument’s sake, you can read this StackOverflow post:
There, a user named bishop claims

"In PHP >= 5.4, the answer is maybe. When you declare the proeprty, PHP optimizes the memory footprint and access path. When you don’t declare the property, the look-up is a hash table scan, and therefore both approaches are equally performant.

So, it’s fastest to declare your properties."

The answer will be different in different languages.

@m_hutley - love the filter_var approach, nice! :slight_smile: The only drawback is that it’s an extension, so it may not be installed everywhere, but it’s probably rare to find a system where it’s not installed. Also, probably it’s good to check isset($_SERVER['SERVER_NAME'] first.

It’s an extension, yes, but so is every array_ function, technically, not to mention the is_numeric function the OP used. :stuck_out_tongue: filter functions are included as part of the baseline PHP install*, so unless you go out of your way to disable them, it’s a safe assumption that they’ll exist.

EDIT: *: Since PHP 5.2

1 Like

So fullstackdev, benanamen, and the most of other members suggest that $_SERVER[SERVER_NAME] is better than the local variable $serverName. Right?

1 Like


You’re still forgetting the quotes.

I would even go further than recommending it. If I see something called $serverName, I assume from the start that it must not be the same as $_SERVER[‘SERVER_NAME’], because why the heck would someone have just copied one variable into another. Now if it needed to be changed, like to upper case, or maybe some filter applied, then sure, there’s a reason not to change it in the $_SERVER array. But to just copy things into other variable names for no reason, that’s certainly not what I’d expect.

(edit - not sure what happened to my dollar signs, but you can assume they’re in there)

1 Like

I guess I’m agnostic on this one. I mean, if I saw someone using $serverName, I wouldn’t think “what a horrible developer!”. Chances are good that I wouldn’t even notice it.

But if I were coding this myself, I’d probably automatically use $_SERVER['SERVER_NAME'].

Remember what @droopsnoot said, “less typing”. Yeah, if I were using this variable 20 times in my function, I might reassign it somewhere. OTOH, in that scenario, I’d have to ask myself whether I was doing something wrong.

Don’t forget @m_hutley’s awesome and tidy solution! filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)

This brings us to what I avoided to stay tight to the actual question.

I took the direct route and assumed the OP was just trying to determine best practice. If this is real code for a real problem, what is the real problem you are trying to solve with this code?

1 Like

Correct me if I am wrong, but there should be little difference between calling $_SERVER[SERVER_NAME] and calling $serverName nearly the same.

there is no speed difference calling a global directly or calling a regular variable

One may argue, that copying to a regular variable, merely for the sake of referencing the value of a super global increasers the memory usage of your script. Tho seeing that this is a string, i can see whatever t the value is making much difference in memory usage.

Then there is readability, and this IS important, but subjective. Assuming the local variable name is descriptive enough; does the name say what the variable contains and/or why.

$_SERVER is an array ; $_SERVER[SERVER_NAME], etc are strings. the usage in your OP is correct.

1 Like

PHP does copy-on-write. So when you create a variable that points to another variable, there is just one in memory, and the second one points to the memory address of the first one. Once you start making changes to the second one a copy will be made and that copy will be changed.

Note that this doesn’t apply to objects. Those are always passed by reference no matter what you do.

1 Like