MasterPHP.in
PHP Tutorial

Strings and Type Casting in PHP


Why Strings Deserve Their Own Lesson

Strings are one of the most frequently used data types in any PHP application — usernames, form input, database results, page content, and error messages are all strings. But PHP handles strings in a few specific ways that trip up beginners, especially around quote types, converting text into numbers, and vice versa. This lesson covers both topics together because type casting most commonly comes up in the context of strings — for example, converting a form field (which always arrives as a string) into a number you can calculate with.


Single Quotes vs Double Quotes

PHP allows you to create strings using either single quotes or double quotes, and the difference between them matters more than it first appears.


php

<?php
$name = "Rohan";

// Double quotes: variables are parsed and replaced with their values
echo "Hello, $name!";        // Output: Hello, Rohan!

// Single quotes: everything is treated as literal text
echo 'Hello, $name!';        // Output: Hello, $name!

Double quotes also support escape sequences like \n (newline) and \t (tab), while single quotes treat these as plain text characters. Because double quotes do extra parsing work, single quotes are marginally faster and are generally preferred when a string contains no variables or special characters.


Concatenation: Joining Strings Together

PHP uses the . operator to join strings, which was introduced briefly in the previous lesson but deserves a closer look here.


php

<?php
$firstName = "Rohan";
$lastName = "Sharma";

$fullName = $firstName . " " . $lastName;
echo $fullName; // Rohan Sharma

// Concatenation assignment, useful for building strings step by step
$greeting = "Hello, ";
$greeting .= $fullName;
$greeting .= "!";
echo $greeting; // Hello, Rohan Sharma!

An alternative to concatenation is string interpolation using double quotes, which is often cleaner for building longer strings:


php

<?php
$age = 25;
echo "My name is $fullName and I am $age years old.";

For inserting array values or object properties directly into a string, curly braces make the syntax clearer and prevent parsing errors:


php

<?php
$user = ["name" => "Rohan"];
echo "Welcome, {$user['name']}!";

Common String Functions You'll Actually Use

PHP includes dozens of built-in string functions, but a small set covers the vast majority of real-world use cases:


php

<?php
$text = "  Hello, PHP World!  ";

echo strlen($text);           // 22 - counts characters, including spaces
echo trim($text);             // "Hello, PHP World!" - removes leading/trailing whitespace
echo strtolower($text);       // "  hello, php world!  "
echo strtoupper($text);       // "  HELLO, PHP WORLD!  "
echo str_replace("PHP", "Laravel", $text); // replaces PHP with Laravel
echo substr($text, 2, 5);     // "Hello" - extracts part of a string
echo strpos($text, "PHP");    // 9 - finds the position of a substring
echo str_word_count($text);   // 3 - counts words

strpos() is worth a special mention: it returns the numeric position where a substring is found, or false if it isn't found at all. This distinction matters because position 0 (a match at the very start) and false (no match) can be confused if you're not careful — always use strict comparison (===) when checking the result of strpos().


php

<?php
$sentence = "PHP is powerful.";

if (strpos($sentence, "PHP") === 0) {
    echo "The sentence starts with PHP.";
}

What is Type Casting?

Type casting is the process of converting a value from one data type to another — for example, turning the string "25" into the integer 25 so it can be used in a calculation. PHP is a loosely typed language, meaning it often converts types automatically behind the scenes, but understanding how to cast types manually gives you control and helps you avoid subtle bugs.


Why Type Casting Matters in Real Applications

The most common real-world scenario is form input. Every value submitted through an HTML form arrives in PHP as a string, even if the user typed a number.


php

<?php
$quantity = $_POST['quantity']; // arrives as a string, e.g. "5"
$price = $_POST['price'];       // arrives as a string, e.g. "199.99"

// Without casting, this would concatenate the strings instead of adding numbers
$total = (int)$quantity * (float)$price;

echo $total; // correctly calculated as a number

Without explicit casting, relying on PHP's automatic conversion can sometimes work, but it becomes unreliable with more complex values — explicit casting removes any ambiguity about what type your code is actually working with.


Casting Between Types

PHP supports casting using a type keyword in parentheses before the value:


php

<?php
$stringNumber = "42";
$floatNumber = "19.99";
$number = 7;
$boolValue = 1;

echo (int)$stringNumber;     // 42 (integer)
echo (float)$floatNumber;    // 19.99 (float)
echo (string)$number;        // "7" (string)
echo (bool)$boolValue;       // true (boolean)
echo (array)"hello";         // converts to an array: ["hello"]

Casting Rules and Edge Cases

Casting doesn't always behave the way beginners expect, especially with strings that mix letters and numbers:


Original Value          Cast To    Result
------------------------------------------------------------
"42"                     (int)      42
"42.9"                   (int)      42 (decimal is dropped, not rounded)
"42abc"                  (int)      42 (PHP reads numbers until non-numeric chars)
"abc"                    (int)      0 (no numeric value found)
""                       (int)      0
0                        (bool)     false
1                        (bool)     true
""                       (bool)     false
"0"                      (bool)     false
"false"                  (bool)     true (non-empty string is truthy!)

That last row catches many beginners off guard: the string "false" is actually truthy when cast to a boolean, because PHP only treats specific values (like an empty string, 0, or null) as falsy — the word "false" as text doesn't count as one of them.


gettype() and Checking Types

Before casting, it's often useful to check what type a value currently is:


php

<?php
$value = "123";

echo gettype($value);        // string
var_dump($value);            // string(3) "123"

// is_ functions for quick checks
var_dump(is_numeric($value)); // true - looks like a number, even as a string
var_dump(is_int($value));     // false - it's still a string type
var_dump(is_string($value));  // true

is_numeric() is particularly useful when validating form input, since it checks whether a value looks like a number regardless of whether it's currently stored as a string or an actual integer/float.


Settype: Casting a Variable Permanently

While (int), (float), and similar casts create a temporary converted value, settype() changes the variable itself:


php

<?php
$quantity = "5";
settype($quantity, "integer");

var_dump($quantity); // int(5) - permanently changed, not just temporarily

What's Next

Now that you understand how to work with and convert string data, the next step is learning how to control repetitive tasks efficiently using loops — a core skill for processing lists of data, validating multiple inputs, or generating repeated output.

Frequently Asked Questions

Double quotes parse variables and escape sequences (like \n) inside the string, while single quotes treat everything literally, including variable names. Single quotes are slightly faster since PHP doesn't need to parse the contents.
PHP reads numeric characters from the start of the string until it hits a non-numeric character, then stops and uses whatever numbers it found. This is different from some other languages that would throw an error for malformed numeric strings.
Yes. All data submitted through HTML forms, whether via GET or POST, arrives in PHP as a string, even if the input looks like a number. This is why explicit type casting is important before performing calculations on form data.
(int)$value creates a temporary converted copy for that specific expression without changing the original variable. settype($value, "integer") permanently changes the variable's type going forward.
PHP's boolean conversion rules only treat specific values as false — an empty string, 0, "0", null, and empty arrays. The text "false" is a non-empty string, so it doesn't match any of those falsy conditions and is treated as true when cast to a boolean.

Share this tutorial