PHP Variables & Constants

In this article, we will learn php variables and also learn php constant with example.

PHP Variables

Variables are also used for storing data, such as text strings, numbers, etc. Over the codes of a script, variable values can be changed. Here are some points to note about variables that are important:

  • The dollar sign ($) is used to declare a variable name.
  • The assignment operator (=) is used to assign a value to a particular variable.
  • Doesn’t need to declare the variable type means datatype. PHP automatically converts the variable to the correct data type, depending on its value.
  • PHP variables can be reused throughout the script.
// Declaring variables
$msg = "Welcome to the PHP beginner Tutorials series";
$number = 10;
// Displaying variables value
echo $msg ;  // Output: Welcome to the PHP beginner Tutorials series
echo $number; // Output: 10


PHP Constants

Constants are likely variables but the key difference is constant has a fixed value on the contrary variable can be changed.

Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value.

// Defining constant
define("SITE_URL", "");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;

Hope you understand!