PHP Introduction Variables and Functions

GeekThis remains completely ad-free with zero trackers for your convenience and privacy. If you would like to support the site, please consider giving a small contribution at Buy Me a Coffee.

In this series of tutorials I am going to teach you not only how to code in PHP, but how to think in PHP. You will learn how to come up with the best methods to solve problems along with the code to go with it. Each tutorial will assume you have read the previous tutorials and fully understand them. Moving along means you have typed sample code out, successfully got it to run and understand why it works.

PHP is a programming language that is popular in web development. PHP can also be used to write console based programs but that is less likely to be used because of the required software to run PHP. How PHP works is there is a “.php” file that gets sent to the PHP application, such as “php.exe” inside of windows. php.exe parses the code and runs the commands present in it. Because PHP does not require a compiler it is much quicker to test code and easier to run because you don’t have to worry about linking libraries.

Setting up PHP

Before we can start typing the code, we need to install the PHP software so we can run our code. This can easily be done in both Windows and Linux. If you are looking to jump right into web development with PHP you should setup a test server, which there is a tutorial for on our website.

Linux Installation

Open up terminal and enter the command:

$ sudo apt-get install php5

Follow the prompts such as entering your password and if you are sure you want to install the packages. After it finished installing you can run the following command to make sure PHP is properly installed.

$ php -v

This command should return the current PHP version and some other information about PHP. If you don’t get anything to return PHP did not install properly.

Windows Installation

Navigate to PHP.net download page located at http://php.net/downloads.php. On this page you should see “Current Stable” release and Windows binaries and source. Download the Zip file, not the source code or Debug Pack. Now extract the Zip file anywhere you can easily access. I have mine in a second hard drive under Z:\Server\php but any location will do.

To check to see if PHP is working properly and so you know how to send programs to PHP open up CMD or Command Prompt.

$ set PATH=%PATH%;Z:\Server\php

Where I have Z:\Server\php put the location you have all the PHP files. The location in the set PATH should be the directory not the executable file. The PATH will only be active in that session of CMD. You can change environmental variables if you want it to stay like that always.

Now run the following command to make sure your PATH is correct.

$ php -v

This command should return the current PHP version and some other information about PHP. If you don’t get anything to return you setup the PATH incorrect.

Creating PHP File

To create your first PHP file, we need to have the PHP tags and save the file as [anything].php

<?php
	// PHP Code Here
?>

As you can see, we open PHP and then at the end of the file we close it. In-between those tags we place our PHP code to execute. The full document doesn’t have to be PHP. You can open and close the PHP tags multiple times to include HTML and other code inside of the file. But keeping your code clean and organized is suggested so having PHP scattered all over the place is not suggested. You may also see some sites suggest PHP tags as follows.

<?
	// PHP Code Here
?>

This is not suggested because the opening tag gets used in other languages as well and could confuse the PHP application and cause syntax errors. When saving, make sure you save your file as a .php extension so you can use this file for websites in the future and to get into the habit of saving the file to the proper extension.

Variables and Functions

With any programming language there are variables which store information, and functions which run equations, processes, commands and saves values to variables. All PHP variables are initiated the same way by using the dollar sign. There are public and private variables that can be used also inside of classes but we will look into that when we talk about PHP Classes.

<?php
	$variable = "a string variable";
	$variable1 = 100;
	$variable2 = 4.3;
	$variable3 = array();
?>

As you can see, the variable initialization is used for all types of variables such as strings, integers, float, double, and arrays. Because of this, PHP programming is easy to learn since variables can be switched between types easily and don’t require extra functions to get a number to a string. Variables and Functions both require semi-colons at the end of the call to notify the end of the statement. Make sure you do not forget them or else you will get errors.

To see what a variable contains and the type of it we use var_dump. Using the previous file, before the closing PHP tags, add the following to see the variables.

var_dump($variable);
var_dump($variable1);
var_dump($variable2);
var_dump($variable3);

To execute the code you need to pass the PHP file to the php application.

$ php [filename].php

The output should return something similar to this.

string(17) "a string variable"
int(100)
float(4.3)
array(0) {
}

In the above code I set variables directly to show how to set variables. But variables can also be modified and set to different values dynamically.

<?php
	$a = 5;
	$b = 7;
	$c = $a + $b;
	var_dump($c);
?>

We set variables A and B to integers. Then C gets set to the sum of those two variables dynamically. This can also be used for strings to append and prepend strings together.

<?php
	$a = "Hello";
	$b = " ";
	$c = "World";
	$d = $a.$b.$c;
	$e = $c.$b.$a;
	var_dump($d);
	var_dump($e);
?>

We created 3 static strings, and then D and E are created with the static values to create a combined string by adding a period in-between the values to combine them. The output of the above code will give you something similar to the following.

string(11) "Hello World"
string(11) "World Hello"

If you want just the string to print out without the extra information such as the variable type and length, you can just “echo” the variable.

<?php
	echo $d;
	echo "\n";
	echo $e;
?>

This will echo variable D, a line break, and then variable E. A line break makes it so each echo will appear on a new line. You could just as easily add ."\n" to variable D and remove the line break echo.

Calling Functions

Now that we can set variables and know a little about how to modify them we can have functions set values to the variables.

<?php
	$a = 0;
	echo $a."\n";
	$a = pow(2,5);
	echo $a;
?>

In the above example, we set the variable A to 0. It is a good idea to always set variables you require on the top of the PHP file to keep track of the variables you are working with, and setting values to them will give them a default value if you happen to not modify them because of an “if” statement or something similar. We then print variable A to show that it is truly 0, and then we set A to the return of the function “pow)”. Pow() allows us to get the power of numbers. The first parameter is the base, and the second parameter is for the exponent. You can see the documentation for the function on the PHP website (here.

Remember that looking up functions in the document is perfectly fine. I’ve been programming PHP for many years and have to look at the documentation still. Learning how to read documentation is very important in programming because remembering every library and function in those libraries is impossible and you will need to use documentation often. Back to the code above, I “echo” out the variable A again after modifying it with the function pow() to show the result.

pow() is just one example of a function you can use to modify variables. Nearly every function will return a value that you can assign to a variable just like above. Parameters in functions can be variables also. Let us create the above code again but using only variables.

<?php
	$a = 0;
	$base = 2;
	$exp = 5;
	echo $a."\n";
	$a = pow($base,$exp);
	echo $a;
?>

This will give you the same result as before, but you can adjust the exp and base variables to easily change the output of the pow() function

Creating a Function

We need to badly create a function to save us time in the future. I want to create a function to take in a string variable, and then echo it with a new line at the end of it so instead of echo we can use our custom function.

We create a function using the format of “function” then our function name. Your function name should be unique, if it isn’t you will get an error. We then create parentheses and inside we pick the variables we want to accept. I created one variable parameter named “str”. In the function I use “str” to get the value that was passed to it. In this case “str” is both “Hello” and “World” but at different times. I then simply call echo of “str” with a newline string at the end of it. This function will not return a value, so if you set it to a variable the variable will not change.

If you ever find yourself repeating a group of functions to perform a task, creating a function for it is highly suggested to easily change all those calls, and to make your code easier to read and cleaner. We simply got tired of printing new lines, so we created a function to do it for us.

In Part 2 of this PHP tutorial I will teach you how to use IF statements and show the use of variables and functions even more.

Part 2: PHP IF Statements and Variables

Related Posts

Prevent Sending HTTP Referer Headers from Your Website

Learn how to prevent your site from sending HTTP referer headers to external websites that you link to with these three different methods.

Process Incoming Mail with PHP Script with Exim

Learn how to process incoming e-mails to your server with a PHP or other script.

PHP - Check if Production or Sandbox

Use PHP to check of your site is on your development server or uploaded to the production server.

Custom Style RSS Feed

Customize the look and feel of your WordPress RSS feed by adding a stylesheet to your RSS XML feed.