Table of contents
1.
Introduction
2.
PHP Constants  
3.
Create a PHP Constant  
4.
Creating a Constant using the define() Function
4.1.
Syntax
4.2.
Example 1
4.3.
Example 2 (Case Insensitive):
5.
Creating a Constant using the const Keyword
5.1.
Syntax
5.2.
Example 1
5.3.
Key Differences Between define() and const:
5.4.
Example 2:
6.
PHP Constant Arrays  
6.1.
Example  
7.
Constants are Global
7.1.
Example
8.
Difference Between Constants and Variables
8.1.
Example Comparison
9.
Frequently Asked Questions
9.1.
1. What is the difference between define() and const in PHP?
9.2.
2. Can constants be redefined or changed in PHP?
9.3.
3. Are PHP constants case-sensitive?
10.
Conclusion
Last Updated: Jan 18, 2025
Easy

PHP Constants

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP Constants are special values in PHP that remain the same during the execution of a script. Unlike variables, constants cannot be changed once they are defined. They are often used to store important information like configuration settings, fixed values, or messages that do not need to be modified. PHP provides an easy way to define constants using the define() function.

PHP Constants

In this article, we will discuss what PHP constants are, why they are important, and how to use them effectively. 

PHP Constants  

PHP constants are identifiers for simple values that remain unchanged throughout the execution of a script. Unlike variables, constants are immutable, meaning once they are defined, their value cannot be altered or redefined. This makes them ideal for storing values that should stay consistent, such as database credentials, API keys, or mathematical values like Pi.  

Constants are case-sensitive by default, but you can make them case-insensitive if needed. They are also global in scope, which means they can be accessed from anywhere in the script, including inside functions or classes.  

For example: 

<?php
define("SITE_NAME", "My Coding Blog");
echo SITE_NAME;
?>


In this example, `SITE_NAME` is a constant with the value `"My Coding Blog"`. Once defined, you can use `SITE_NAME` anywhere in your script, & its value will always remain the same.  

Create a PHP Constant  

Creating a PHP constant is straightforward. You use the `define()` function, which takes two mandatory parameters & one optional parameter:  

1. Name of the constant: This is the identifier you’ll use to refer to the constant. By convention, constant names are written in uppercase letters to distinguish them from variables.  
 

2. Value of the constant: This is the fixed value assigned to the constant.  
 

3. Case-insensitivity (optional): By default, constants are case-sensitive. If you want to make them case-insensitive, you can set this parameter to `true`.  
 

Let’s see how you can create a constant step-by-step:  

<?php
// Step 1: Define the constant
define("WELCOME_MESSAGE", "Hello, welcome to our website!");


// Step 2: Use the constant
echo WELCOME_MESSAGE;
?>


In this example:  

- We define a constant named `WELCOME_MESSAGE` with the value `"Hello, welcome to our website!"`.  
 

- We then use the `echo` statement to display the value of the constant.  
 

If you try to change the value of the constant later in the script, PHP will throw an error. For example:  

<?php
define("WELCOME_MESSAGE", "Hello, welcome to our website!");
WELCOME_MESSAGE = "New message"; // This will cause an error
?>


This immutability is what makes constants reliable for storing fixed values.  

Creating a Constant using the define() Function

The define() function is one of the most common ways to create constants in PHP. It allows you to assign a name and a value to a constant that remains the same throughout the script.

Syntax

define(string $name, mixed $value, bool $case_insensitive = false);

 

  • $name: The name of the constant (written in uppercase by convention).
     
  • $value: The value assigned to the constant.
     
  • $case_insensitive: If set to true, the constant’s name will be case-insensitive (not recommended for modern PHP).

Example 1

<?php
// Creating a constant
define("PI", 3.14);
// Using the constant
echo "The value of PI is: " . PI;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

The value of PI is: 3.14

Example 2 (Case Insensitive):

<?php
// Creating a case-insensitive constant
define("GREETING", "Welcome to Coding Ninjas!", true);

// Accessing the constant in different cases
echo GREETING;   
echo greeting; 
?>
You can also try this code with Online PHP Compiler
Run Code

 
Output: 

Welcome to Coding Ninjas!
Welcome to Coding Ninjas!

 

However, using case-insensitive constants is discouraged in modern PHP versions.

Creating a Constant using the const Keyword

The const keyword is another way to define constants. Unlike define(), constants created with const are always case-sensitive.

Syntax

const NAME = value;

 

  • NAME: The name of the constant.
     
  • value: The value assigned to the constant.

Example 1

<?php
// Creating a constant using const
const WEBSITE = "www.codingninjas.com";


// Using the constant
echo "Visit us at: " . WEBSITE;
?>
You can also try this code with Online PHP Compiler
Run Code

Output:

Visit us at: www.codingninjas.com

Key Differences Between define() and const:

  • const is used for constants declared inside classes and is evaluated at compile time.
     
  • define() can be used anywhere, even within conditional blocks.

Example 2:

<?php
if (true) {
    define("CONSTANT_A", "Hello from define");
    // const CONSTANT_B = "Hello from const"; // This will throw an error
}

echo CONSTANT_A;  
?>
You can also try this code with Online PHP Compiler
Run Code


Output: 

Hello from define

PHP Constant Arrays  

PHP constants are not limited to storing simple values like strings or numbers. They can also store arrays, which makes them incredibly versatile for managing multiple related values. This is particularly useful for configuration settings or predefined data sets.  

To define a constant array, you use the `define()` function, just like with simple values. However, the value you assign will be an array.  

Here’s how you can create & use a constant array:  

<?php
// Step 1: Define a constant array
define("COLORS", [
    "red",
    "green",
    "blue"
]);
// Step 2: Access the constant array
echo COLORS[0]; // Output: red
echo COLORS[1]; // Output: green
echo COLORS[2]; // Output: blue
?>

  In this example:  

- We define a constant named `COLORS` that holds an array of three color names.  
 

- We then access the elements of the array using their indices (`0`, `1`, & `2`).  
 

You can also use associative arrays with constants. For example:  

<?php
// Step 1: Define a constant associative array
define("USER_DETAILS", [
    "name" => "John Doe",
    "age" => 25,
    "email" => "john.doe@example.com"
]);


// Step 2: Access the constant associative array
echo USER_DETAILS["name"]; // Output: John Doe
echo USER_DETAILS["age"];  // Output: 25
echo USER_DETAILS["email"]; // Output: john.doe@example.com
?>

  

In this example:  

- We define a constant named `USER_DETAILS` that holds an associative array with user information.  

- We access the values using their respective keys (`name`, `age`, & `email`).  

Example  

Now, we’ll create a PHP script that uses constants for configuration settings & displays information based on those constants. This example will include both simple constants & constant arrays.  

Here’s the complete code:  

<?php
// Step 1: Define simple constants
define("WEBSITE_NAME", "My Coding Blog");
define("WELCOME_MESSAGE", "Welcome to our website!");
define("PI", 3.14159);


// Step 2: Define a constant array for navigation links

define("NAV_LINKS", [
    "Home" => "/",
    "About" => "/about",
    "Contact" => "/contact"
]);


// Step 3: Define a constant associative array for user details

define("USER_DETAILS", [
    "name" => "John Doe",
    "age" => 25,
    "email" => "john.doe@example.com"
]);


// Step 4: Display the website information

echo "<h1>" . WEBSITE_NAME . "</h1>";
echo "<p>" . WELCOME_MESSAGE . "</p>";
echo "<p>The value of PI is: " . PI . "</p>";


// Step 5: Display the navigation links

echo "<h2>Navigation Links:</h2>";
echo "<ul>";
foreach (NAV_LINKS as $link_name => $link_url) {
    echo "<li><a href='" . $link_url . "'>" . $link_name . "</a></li>";
}
echo "</ul>";


// Step 6: Display user details

echo "<h2>User Details:</h2>";
echo "<p>Name: " . USER_DETAILS["name"] . "</p>";
echo "<p>Age: " . USER_DETAILS["age"] . "</p>";
echo "<p>Email: " . USER_DETAILS["email"] . "</p>";
?>

  

In this code: 


1. Simple Constants:  

   - `WEBSITE_NAME`, `WELCOME_MESSAGE`, & `PI` are simple constants storing a string, another string, & a numeric value, respectively.  


2. Constant Array:  

   - `NAV_LINKS` is a constant array that stores navigation links as key-value pairs. The keys are the link names, & the values are the URLs.  


3. Constant Associative Array:  

   - `USER_DETAILS` is a constant associative array that stores user information like name, age, & email.  


4. Displaying Information:  

   - The script uses `echo` to display the website name, welcome message, & the value of PI.  

   - It also loops through the `NAV_LINKS` array to display the navigation links as an unordered list.  

   - Finally, it displays the user details stored in the `USER_DETAILS` array.  


Output:  

When you run this script, it will generate the following output:  

HTML

<h1>My Coding Blog</h1>
<p>Welcome to our website!</p>
<p>The value of PI is: 3.14159</p>


<h2>Navigation Links:</h2>
<ul>
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>


<h2>User Details:</h2>
<p>Name: John Doe</p>
<p>Age: 25</p>
<p>Email: john.doe@example.com</p>

 
This example shows how constants can be used effectively in a real-world scenario. 

Constants are Global

One of the biggest advantages of constants is that they are automatically global. This means that once defined, a constant can be accessed from anywhere in the script, including inside functions, classes, or loops.

Example

<?php
// Defining a constant
define("LANGUAGE", "PHP");
function showLanguage() {
    // Accessing the constant inside a function
    echo "The programming language is: " . LANGUAGE;
}
showLanguage();
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

The programming language is: PHP


Since constants are global, you don’t need to use special keywords like global or pass them as arguments to functions. They are accessible throughout your code.

Difference Between Constants and Variables

Although constants and variables both store values, they have some significant differences:

ParametersConstantsVariables
ValueFixed and cannot be changed.Can be reassigned.
DeclarationUse define() or const.Use $ symbol.
ScopeGlobal by default.Local by default.
Case SensitivityCase-insensitive (optional) or case-sensitive (default).Always case-sensitive.

Example Comparison

<?php
// Constant
define("MAX_USERS", 100);


// Variable
$maxUsers = 50;

// Output
echo "Maximum users (constant): " . MAX_USERS . "\n";
echo "Maximum users (variable): " . $maxUsers . "\n";


// Trying to modify values
// MAX_USERS = 200; // This will throw an error
$maxUsers = 200;
echo "Updated maximum users (variable): " . $maxUsers;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

Maximum users (constant): 100
Maximum users (variable): 50
Updated maximum users (variable): 200


Constants are ideal for values that should remain unchanged, such as configuration settings or fixed values like PI or website URLs.

Frequently Asked Questions

1. What is the difference between define() and const in PHP?

The define() function can create constants anywhere in your code, even conditionally, while const is used for constants defined at compile time and cannot be conditional.

2. Can constants be redefined or changed in PHP?

No, once a constant is defined, it cannot be changed or redefined.

3. Are PHP constants case-sensitive?

By default, constants are case-sensitive. You can make them case-insensitive using the third parameter of the define() function, though this practice is not recommended.

Conclusion

In this article, we discussed PHP constants, how to define them using define() and const, and how they differ from variables. Constants are an important part of writing reliable and efficient code, especially when dealing with fixed values. With the provided examples, you should now be able to use constants confidently in your PHP projects.

Live masterclass