You are on page 1of 7

PHP VARIABLES

By: Yassen Hadhoud


◦ A variable stores a value of any type, e.g., a string, a number, an array,
or an object.

What’s ◦ A variable has a name and is associated with a value. To define a


variable, you use the following syntax:

Variable? ◦ $variable_name = value;


When defining a variable, you need to follow these rules:
◦ 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)

02/26/2024
Example 1
◦ $txt = "W3Schools.com";
◦ echo "I love " . $txt . "!";
Example
Example 2
o $x = 5;
o $y = 4;
o echo $x + $y;

02/26/2024
◦ PHP supports the following data types:

Variable Types ◦ String


◦ Integer
◦ Float (floating point numbers - also called double)
◦ Boolean
◦ Array
◦ Object
◦ NULL
◦ Resource

02/26/2024
◦ To get the data type of a variable, use the var_dump() function.
Example
Get the Type ◦ The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x);
Example 2 :
<?php
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
?>
02/26/2024
◦ A string is a sequence of characters, like "Hello world!".
◦ Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.
PHP Strings String Length
The PHP strlen() function returns the length of a string.
 Example
Return the length of the string "Hello world!":
echo strlen("Hello world!");
Word Count
The PHP str_word_count() function counts the number of
words in a string.
 Example
Count the number of word in the string "Hello world!":
echo str_word_count("Hello
02/26/2024 world!");
String Concatenation
PHP - ◦ To concatenate, or combine, two strings you can use the .
Concatenate operator:
Strings String Length
The PHP strlen() function returns the length of a string.
 Example
 $x = "Hello";
 $y = "World";
 $z = $x . $y;
 echo $z

02/26/2024

You might also like