Logo
Unit 2 – PHP Basics: Variables and Data Types

PHP Basics: Variables and Data Types

Duration: 5 minutes

Greetings, PHP enthusiasts!

Variables lie at the heart of programming, acting as containers for storing data values. In PHP, a variable starts with the $ sign, followed by its name. However, not all data is the same; PHP has various data types to help classify and better utilize this data.

Ready to unveil the power of PHP variables and understand their diverse types? Let’s embark!

Variables in PHP

In PHP, a variable:

  • Starts with the $ sign, followed by its name.
  • Can have a short name (like $a) or a more descriptive name (like $userAge).
  • Only needs to be declared once, but can be used many times in a script.

Example:

$name = "Zahwah";
echo $name; // Outputs: Zahwah

Understanding Basic Data Types

PHP supports various data types, and here, we’ll touch upon some of the basics:

  • String: A sequence of characters, like “Hello, World!”.
$stringVar = "This is a string.";
echo $stringVar; // Outputs: This is a string.

  • Integer: A whole number, without decimals, that can be negative or positive.
$intVar = 23;
echo $intVar; // Outputs: 23

  • Boolean: Represents two possible states, TRUE or FALSE.
$boolVar = true;
echo $boolVar; // Outputs: 1 (which represents TRUE)

  • Array: Contains multiple values under a single name.
$arrayVar = array("Apple", "Banana", "Cherry");
echo $arrayVar[1]; // Outputs: Banana

  • Object: Allows for bundling variables and functions into a single entity.
class Fruit {
function sayHello() {
echo "Hello from the Fruit class!";
}
}
$fruit = new Fruit();
$fruit->sayHello(); // Outputs: Hello from the Fruit class!

  • Null: A special data type that can have only one value: NULL. It represents no value or no data.
$nullVar = NULL;
echo $nullVar; // Outputs nothing

Exercise

Time to get hands-on with what we’ve learned:

  • Declare a string and echo it.
  • Declare an integer and display its value.
  • Create a boolean variable, and check its output.
  • Formulate an array with at least three items, and print the second item.
  • Designate a variable with a null value and try echoing it.

Conclusion

Congratulations! You’ve now grasped the foundational concept of variables and their diverse data types in PHP. These building blocks are paramount as you continue to dive deeper into the world of PHP programming.

Eager to uncover more? Stay tuned, and let’s keep the PHP momentum going!

Next Tutorial: PHP Basics: Operators

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!