Php variables and text

Lesson 3 — Variables and type system in PHP

In the previous lesson, Installing Apache + MySQL + PHP on Windows and making an app, we installed and prepared everything necessary to program in PHP. In today’s lesson, we’re going to take a look at the overall basic syntax and work with variables.

Echo()

Let’s quickly go over what we covered in the previous tutorial:

   "Content-Type" content="text/html; charset=UTF-8">  echo("This text was inserted into a website by PHP"); ?>  

As we already know, a PHP script looks just like a regular HTML website. The main difference being that it has the .php extension, which allows it to contain the tags (directives). The code within these tags will be executed by the PHP module on the server. The result, generated by the code, will be inserted at that place.

The echo() command prints the given text into the website. Echo() is a function. We write parentheses after the name of every function and enter its input parameters within the parentheses. In this case, the parameter that echo() takes is the text to be printed. Even if the function doesn’t require any parameters, you have to include the parentheses (empty ones). PHP is based on functions and it provides quite a lot of them. For the most part, we don’t have to make our own functions, we just call a function that PHP provides and have it do what we need. We can also use objects instead of functions, but we won’t go into that until later. Bear in mind, that we won’t be able to create complex applications without them. This course will be followed by several others that will go into some of the more advanced techniques.

*Note: We can omit the parentheses when using echo() , but you will not be able to do the same thing with most functions. I find it better to use them everywhere rather than have them missing and have the code misbehave.

We pass text to the echo() function through its parameter (in the parentheses). In programming, we call text strings. We declare strings using quotation marks, both single or double. We do that so that PHP doesn’t mistake them for other commands. For example, when we write:

PHP knows that the second echo is text and will print it instead of calling the function. Each command ends with a semicolon. We write commands on separate lines. PHP’s syntax is based on the C language, as a matter of fact, PHP itself is programmed in C. Knowing this, you may not be surprised to know that it is very similar to other programming languages that derived from the C language, for example, Java and C# .NET. If you have experience working with any of those languages, you’re ahead of the crowd. Either way, we’ll explain everything from the ground up.

There are no traces of PHP on the website that the user sees. All that it contains is what was generated by PHP. So users are never able to access or see the PHP code. The HTML website generated by the script above looks like this:

 html>   http-equiv="Content-Type" content="text/html; charset=UTF-8">  This text was inserted into website by PHP 

PHP doesn’t replace HTML in any way — it is a tool for generating HTML files based on requests. In most cases, we set up HTML templates into which we add content dynamically. We usually don’t know what the content will be until the request is sent as the content changes quite often (e.g. messages in a guestbook). The content is usually loaded from a database.

As some of you may now be saying, » why even bother using PHP if we could make the example above without it»? To put these comments to rest, we will add dynamical functionality to the script.

Variables

You should recall the word «variable» from grade school. For all of you non-programmers — it’s a place in the computer memory where we can store data and still be able to work with it later. We can name variables whatever we want as long as we won’t add spaces or accent characters. In PHP, We write a dollar ( $ ) sign before every variable.

Let’s create a few variables in the PHP part of the website and fill them with values.

$greeting = "Hello"; $age = 15; $pi = 3.14;

As you can see, I have chosen variable names based on what is stored in them. There is nothing worse than storing an age to variable $a , a greeting to $b , etc.. When you name variables like that, you will end up making the script unecessarily confusing. On the other hand, if you have 2 numbers and you name them $a and $b — you’ll be fine. We can easily print the content of a variable using the echo() function. Let’s add a couple of more lines to our code:

 $greeting = "Hello"; $age = 15; $pi = 3.14; echo($greeting); echo('
'
); echo($age); echo('
'
); echo($pi); echo('
'
);

You should see the following output:

As you can see, we only use quotes for string values. Numbers and/or variable names are written without them.

Data types

Each variable is of a particular type, referred to as data types. In the script shown above, we created variables of the 3 basic data types. The greeting variable is a string , which we have already gone covered. The $age variable is an int which represents a whole number. The $pi variable is a double . You may occasionally encounter the float data type, in PHP, both of these types are the same and represent a decimal number.

PHP is a dynamically-typed language. That means that we don’t have to specify the data type of a variable like we have to in languages like C. PHP determines the data type on its own based on the content it is filled with. PHP also automatically converts between types. Theoretically, you wouldn’t even have to know that variables have data types. However, you may run into situations where PHP converts variables in a way that you didn’t expect, in which case you will need to understand what is happening behind the scenes.

Adding numbers and concatenating strings

As you may have guessed, we can use basic arithmetic, parentheses or other variables when working with numbers in PHP.

 $r = 10; $area = 3.14 * $r * $r; echo("Circle's area is $area cm2"); 

The code above will create a variable named $r with its value set to 10 . We use this value when assigning a value to the $area variable. The value of the $area variable is printed using the echo() function along with some other text.

As you can see, we can easily add variable content into strings, however, it works only with double quotes. If the string was declared with apostrophes (single quotes), it’d be printed as it was declared and the variable won’t be inserted. We printed the upper index for cm 2 using the HTML tag. As you may have guessed, the radius would be entered using a form in the visual part of the application. Which we will get to eventually, I promise.

As I said, PHP converts between different data types automatically. Try it out on a couple of different variables:

 $a = 10; $b = "20"; $c = $a + $b; echo($c); 

Although variable $b is text, PHP converts it to a number as soon as it finds out that we want to add it ( + ) to another number. We’d get the same result even if we did this:

 $a = 10; $b = "20 is my age"; $c = $a + $b; echo($c); 

Although setting it up that way is pretty wild, I just showed you so you could see how PHP handles variable conversions.

We are also able to concatenate strings using the dot operator ( . ) :

 $a = 10; $b = 20; $sentence = "Hello, I'm"; $sum = $a + $b; $concatenated = $a . $b; echo("Here we sum numbers A and B: $sum"); echo('
'
); echo("Here we concatenate strings A and B: $concatenated"); echo('
'
); echo('And one more example: '); echo($sentence . " " . $b . " years old.");

Based on the program output, you now see the difference between adding numbers and concatenating strings. We’re still in HTML, if we want a new line, we add one using the HTML tag for a new line.

I look forward to seeing you all in the next lesson, Strings and arrays in PHP, where we’ll introduce you to arrays. Today’s exercises can be downloaded from the link below.

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

Downloaded 116x (1.38 kB)
Application includes source codes in language PHP

Источник

PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

After the execution of the statements above, the variable $txt will hold the value Hello world! , the variable $x will hold the value 5 , and the variable $y will hold the value 10.5 .

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ( $age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

The following example will produce the same output as the example above:

Example

The following example will output the sum of two variables:

Example

Note: You will learn more about the echo statement and how to output data to the screen in the next chapter.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter.

Источник

Variables and Types

To define a variable, simply use the following syntax:

We have just defined a variable named x with the number 1, a variable named y with the string «foo» and a variable name z with the boolean value True. Once they are defined, we can use them in the code.

PHP has many types of variables, but the most basic variable types are integer (whole numbers), float (real numbers), strings, and booleans.

PHP also has arrays and objects which we will explain in other tutorials.

Variables can also be set to NULL, which means that the variables exist, but do not contain any value.

Operators

We can use simple arithmetic operators to add, subtract or concatenate between variables.

We can also print out PHP variables using the echo command (you can try it out now).

For example, let’s sum up two numbers, put the result in a new variable, and print out the result.

$x = 1; $y = 2; $sum = $x + $y; echo $sum; // prints out 3 

String formatting

Like Perl, PHP double quoted strings can format strings using defined variables. For example:

$name = "Jake"; echo "Your name is $name"; // prints out Your name is Jake 

Exercise

Part 1

Define the variables name and age so that a line would be printed out saying the following sentence:

Hello Jake. You are 20 years old.

Notice that the code contains a special character sequence at the end called a newline — \n . This sequence will cause the next line printed out to be printed out on the next line. For web development, this is not important, since we use HTML tags for this purpose.

Part 2

Sum up the variables x and y and put the result in the sum variable.

Источник

Читайте также:  Python socket asyncio server
Оцените статью