Skip to Content

Variables in PHP: Usage, Examples & Data Types

Variables in PHP are pieces of data identified by a name and have the ability to store data of many types. PHP variables are declared using a dollar sign $ and a name consisting of alphanumeric characters and underscores _.

Examples

There are many data types available when creating variables in PHP. Strings, for example, are assigned with either single or double quotes:

$name = 'Orangeable';
$name = "Orangeable";

While integers and floating-point number assignments contain no quotation marks:

$num = 47;
$num = 3.1415279;

Data Types

Here is a list of all the available data types and examples when creating variables in PHP:

  • bool: boolean values, returning either true or false.
  • int: integer numbers containing no decimals.
  • float: floating-point numbers containing decimals.
  • string: strings of text containing alphanumeric characters.
  • array: nodes of data assigned with indexes, or positions within the contained array.
  • object: data containing key/value pairs.
  • null: no value assigned

PHP is not strict with data types. A variable assigned as a string could later be recreated as a numeric value or vice versa.

Output Variable Values

You can use the var_dump() method to output any given variable's data type and value. For example, the following code snippets show different outputs depending on their assumed data types.

For example, a string output looks like this:

$name = "Orangeable";

var_dump($name);
// string("Orangeable");

And a numeric output looks like this:

$num = 47;

var_dump($num);
// int(47)

Case Sensitivity

You can name your variables with underscores or use camel case, but keep in mind these variable names are case sensitive, meaning a variable named $name is different than $Name. These two variables with different character cases can each contain a unique value.

It's highly recommended you follow a standard practice when naming your variables. I generally use all lowercase letters with underscores like $my_name, but it's industry standard to use camel case like $myName. Stick with your decision for consistency.

Conclusion

You have a lot of flexibility when creating and assigning variables in PHP. Just keep the above rules and recommendations in mind, and you'll be an expert with variables and data types in no time.

Created: August 29, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.