Variables

Variables

Let's learn more about variables

The drones need to send its coordinates every 5 minutes to you and the agents. So we need a way of storing these coordinates that are sent. In PHP, we can store messages in a Variable.  You can think of a variable as a uniquely named/labeled container which we can use to store data. 

This data in a variable can be 

  • numbers, 
  • sentences, 
  • symbols, 
  • a collection of numbers, etc. 

To create a variable in PHP you have to give it a name. Note that all variable names must start with a dollar sign “$”. Giving it a value (i.e., assigning the variable its data) is optional at this point. But you have to give it a value before you use it later in your code. Variables are uniquely labeled. This means that in your PHP script, you cannot have variables with the exact same name. 

(Hover over the numbers for details)

Note

Variable names ARE case sensitive

This means that a variable with the name “$MESSAGE” is NOT the same as a variable with the name “$message”.

PHP syntax

Let's see an example

We want to create a variable called “spaceshipName” and give it the value of Pluto. How would we do that?

Note: in PHP, all lines of code must end with a semicolon.

Let’s play around with variables in the PHP compiler below. You’ll see our PHP code created around variables. 

  • $numberOfPassengers is the variable with the number of  passenger of the lost spaceship
  • $numberOfCaptains is the variable with the number of  captains of the lost spaceship

Change the values of the variables value. 

And  add echo statements to print out the variable values. Be creative and play around. Click run to see what happens.

Now it is time to practice,

Click on the “fork me” below to edit the PHP code directly.

Remember – your task is to help Agent Gail to build the drone’s software that will help locate spaceship Galaxy X. For the drones to detect spaceship Galaxy  X, they would need to have the name of the spaceship in their database.

Now create a variable that would store the name of the spaceship, the lost spaceship is called Galaxy X as you know.

Click on the “fork me” below to edit the PHP code directly.

Great job – you’ve learnt about variables and data types. And created a storage system for Agent Gail’s drones. 

Next up – let’s learn about Data Types in PHP. This will help us create a more complex storage system for our drones.

Next: Let's learn about data types.