09.24.07

Understanding PHP String Variables

Posted in PHP at 12:05 pm by admin

Understanding PHP String Variables

If you are interested in truly coming to grips with the awesome power of PHP, then one of the things that you are going to have to do is learn how variable systems within the programming language work. These variable systems allow you to execute the most complicated of PHP scripts and if you learn them at the start of your PHP training then it will be much easier to figure out exactly what to do about them later.

In order to understand how variables work and what the appropriate syntax for variables is, let us look at the example of PHP code that we produced in the article that discussed PHP being a loosely typed language:

<?php
$text=”PHP Rocks”;
$number=1
?>

While this is most certainly a solid piece of code, you will notice that the variable $number is not a string value but rather an integer value. So let’s get rid of that for a moment and add the echo command to the PHP script so that we can actually get it to execute something.

<?php
$text=”PHP Rocks”;
Echo $text;
?>

If you were to execute the above script on your server, the output would simply be the phrase PHP Rocks; the same as if you were to simply type the phrase PHP Rocks into your actual HTML file. This might seem a bit simplistic, but later on when you are programming exceptionally complicated PHP scripts, you are going to need to know this information by heart. To finish off the lesson, let’s add the $number variable back in but make it a string be adding three more digits to the value.

<?php
$text=”PHP Rocks”;
$number=”1111”;
?>

Now, if we want to put these two strings together it requires the use of the concatenation operator, which has the syntax of a period in PHP.

<?php
$text=”PHP Rocks”;
$number=”1111”;
Echo $text.$number
?>

This will produce the following output: PHP Rocks1111

If you want to separate the two strings with a space, then you need to actually concatenate the space into the actual PHP script:

<?php
$text=”PHP Rocks”;
$number=”1111”;
Echo $text.” ”.$number
?>

This will produce the following output: PHP Rocks 1111

In that last example, the quotation marks surround a single space, which is concatenated to the two string variables through the use of two concatenation operators. When you see PHP scripts capable of executing in such a way that the output is long string values, then chances are there are quite a few concatenation signs involved in that output.

Scriptycan is a great software repository featuring both free and commercial PHP scripts and applications for developers and programmers.

Leave a Comment

You must be logged in to post a comment.