Chains or strings in PHP

General explanations about strings in PHP. How to use strings in PHP, good practices and tricks to improve the code with this type of data.

One of the most common data types in most languages ​​are strings. We can also know them with the name of strings or “character strings”. They are nothing more than information that contains text, with alphanumeric characters, any mixture of alphabetic characters, symbols and numeric characters.

To put it in other words, in general, when we save any text in a variable, what we are technically saving are strings. It is a very important type of data, since much of the information we have to work with in applications is text.

To assign a string type content to a variable, we will write it in quotes, validating both double quotes and single quotes. In code it gives rise to statements of this type:

$string=”This is the information of my variable of type string”;

If we want to display the value of a variable or any message on the screen, we will use the echo statement as we have already seen in various examples so far in :

echo $string; // would output “This is the information of my variable”

Note: In PHP there are several mechanisms to produce output (write text on the web page). The “echo” statement is the simplest there is, valid when you’re inside PHP code.

We can pass the echo statement not only a variable of type string, because in reality it outputs anything on the screen: If it is not a string, it will do what it can to produce an adequate output. We can even pass it a string literal:

echo “This is the information of my variable”; // would give the same result

Note: In programming languages ​​in general, a “literal” refers to a piece of data written as it is in the code. A string literal is written in quotes, but a numeric literal is written without the quotes.

String literals with double quotes or single quotes

Something characteristic of PHP is that it allows us to use both single quotes and double quotes and, depending on how we have done it, PHP will interpret the strings in a different way. It is something that we must learn as soon as possible when working in PHP, because if not, it may give us some problems or situations arise in which the result of a program is not what was expected.

Double-quoted strings

Using double quotes to delimit PHP strings will make the language behave in a more “intelligent” way. The highlight is that the variables that we place inside the strings will be replaced by the values. It is better to see it with a code.

See also  CSS Border Styles

$website = “WebDevelopment”; $string = “Welcome to $website”; echo $string;

That code will output “Welcome to WebDesarrollo”. That is, PHP will interpolate the value of the variable $website in the $string variable, replacing $website with its corresponding value: “WebDevelopment”.

Within double-quoted strings are a large number of escape characters, by which we can place things like newlines, tabs, or “$” symbols in strings that would not be considered the start of a variable name. We will give more detail about this later.

Strings with single quotes

When you enclose a string literal in single quotes, things change quite a bit. Most notably, none of your variables will be replaced by their value. You can see it in the following source code:

$website = ‘WebDevelopment’; $string=”Welcome to $website”; echo $string;

This source code is almost the same as the previous one, except that we are using strings delimited by single quotes. The output is significantly different, in this case it would show us “Welcome to $siteweb”, since it does not interpolate the variable.

As you can see, inside a string indicated with single quotes you can’t insert variable values ​​so easily, you would have to break the string and concatenate with the variable. We’ll talk about how to concatenate or join strings in a moment, but for the sake of the example, to get the result of the equivalent script but with double quotes, you would have to write something like this:

$website = ‘WebDevelopment’; $string=”Welcome to ” . $website; echo $string;

What to use, single or double quotes?

The answer is simple. It’s generally recommended to use single quotes, since PHP will have less trouble using them, since it won’t try to substitute variable values ​​into them. Only if you want to take advantage of easy variable interpolation would you recommend using double-quoted strings, since you will generate much easier code for humans to read and maintain for the life of the application.

string concatenation

We can juxtapose or concatenate multiple strings using the string concatenation operator, which has the dot “.” symbol:

$string1=”Dog”; $string2=” bites”; $string3=$string1.$string2; echo $string3; //The result is: “Dog bites”

Although we have already said it, using double quotes you could place those variables inside our string. Here is another example:

$a=55; $message=”I am $a years old”; echo $message; //The result is: “I am 55 years old”

The question we can ask ourselves now is… How can I do so that instead of the value “55” I get the text “$a”? In other words, how is it done so that the $ symbol does not define a variable but is taken as is. This question is all the more interesting because in some of the scripts this symbol must be used for a simple commercial reason (payment in dollars for example) and if we write it as it is, the computer will think that what comes after it is a variable being which is not.

See also  Understand, install, and configure Git

escape characters

To include the $ symbol, the backslash, and other characters used by the language within strings and not confuse them, escape characters are used.

To insert an escape character we have to indicate it starting with the backslash symbol (backslash) and then the escape character we want to use.

The available escape characters depend on the type of string literal we are using. For strings with double quotes, many more escape characters are allowed. You find them in the following table:

These newlines and tabs only have an effect on the code and not on the text executed by the browser. In other words, if we want our executed text to change lines we have to introduce an echo “
” and not .

Note: The line break escape character only changes lines in the HTML code created and sent to the browser when the page is executed on the server. That line break has no value in the HTML, so you would only see it when examining the source code produced by running the script.

There are far fewer escape characters for strings expressed in single quotes. First, because they are not necessary (like the $ symbol, which cannot be confused with the beginning of a variable, since it does not take them into account) and second, because they are simply not available.

Below you can see the table of escape characters allowed in a string enclosed by single quotes:

Complex brace syntax

Another useful thing to learn when working with strings is the ability to interpolate complex values ​​of somewhat special variables. In the PHP documentation they call this “complex syntax”, but don’t panic because it’s really quite simple.

Look at the following code:

$array = array(1, 2, 40, 55); $string = “Position three contains the data $array”; echo $string; //write Position three contains data 40

Here there is no problem when expanding the value of position 3 of the array in the string, using (yes) double quotes. Even though the array needs an index, PHP knows that what it has to display there is a cell in the array. But now look at the following code:

$array = array(‘one’ => 1, ‘two’ => 2, ‘three’ => 40, ‘four’ => 55); $string = “The position ‘three’ contains the data $array”; //this produces an error!!

See also  Types of SQL statements and their syntactic components

In this case, our script will produce an error when interpreted by PHP, since an array with an alphanumeric index (associative array) is not able to process it correctly when we write it into a string.

To overcome this situation, the aforementioned complex syntax of braces comes into play. We are simply going to write the associative array that we want PHP to replace enclosed in braces. So PHP will recognize it perfectly.

$array = array(‘one’ => 1, ‘two’ => 2, ‘three’ => 40, ‘four’ => 55); $string = “The position ‘three’ contains the data {$array}”; //Now works fine echo $string; //write Position ‘three’ contains data 40

At first, this syntax of the braces may not seem very useful to you, but we assure you that in your day-to-day with PHP you will use it a lot, because many times in PHP you have data that comes from associative arrays, or from other sources. struct types not interpolating correctly when you are writing values ​​inside strings (always with double quotes).

Although we haven’t covered yet how to receive data that comes to you from forms, we can preview some simple code here. Imagine that you are receiving a form and you have a field called “phone” in that form. On the page you receive that form, it comes to you as $_POST. If you want to put that phone inside a string you could use code like this:

$phonePrefix = “(+34) {$_POST}”;

string functions

Strings can also be handled by functions of all kinds. PHP is a very rich language in this sense, which includes many possible actions that we can perform on them just by executing a function: Divide them into words, remove excess spaces, locate sequences, replace special characters with their corresponding HTML, etc.

For example, here you can see the use of a very useful function when programming in PHP and producing output in HTML, in which we change all the special characters of the HTML entities (useful to avoid HTML code being injected into the document that we do not want to appear formatted, but written on the page with its tags and all).

$originalString=”I like PHP“; $touchedString = htmlspecialchars($originalString); echo $touchedString; //write <b>Like PHP</b>

We’ll see some new examples of string functions later. But as we always recommend, remember to also stay informed with the documentation: .

Loading Facebook Comments ...
Loading Disqus Comments ...