Variables are ways we can define values we can use in other places in our code. We can also use variables in multiple places in our code, unlike hard coded values.
When we refer to something as a “hardcoded value” we mean a value thats passed straight into a function that we’re want to use, without a variable.
Given following code
<!-- index.html -->
<html>
<head>
</head>
<body>
<?php
echo "<h1>Hello world</h1>";
?>
</body>
</html>
We want to add a couple of different variables that prints out an h1 tag containing a given string of our choice.
Variables in PHP are dynamically typed, which means variable types do not need to be explicitly defined.
We’re currently rendering an h1 tag with the text Hello World inside it using PHP. We move this over to its own variable. Lets make the name of this variable message.
To create a variable in PHP you need to create a dollar sign in front of the variable name, and then have your variable equal to the value you want.
$variable_name = "my variable value";
And then we print out the string
To convert our h1 tag into a variable we would just follow the same syntax.
$header_string = "<h1>Hello world</h1>";
And then use the variable in our echo instead of the string.
<?php
$header_string = "<h1>Hello world</h1>";
echo $header_string;
?>
If we have already declared a variable in PHP we can change our variable’s value like this
<?php
$header_string = "<h1>Hello world</h1>";
$header_string = "<h1>Hi Universe</h1>";
echo $header_string;
?>