Scalar Types
PHP Data Types Overview
| Category | Types |
|---|---|
| Scalar | int, float, string, bool |
| Compound | array, object, callable, iterable |
| Special | null, resource |
Integer (int)
<?php
$quantity = 42; // Decimal
$hex = 0xFF; // Hexadecimal (255)
$octal = 0777; // Octal (511)
$binary = 0b10101010; // Binary (170)
$underscore = 1_000_000; // Readable large number (1000000)
// Integer limits
echo PHP_INT_MAX; // 9223372036854775807 (64-bit)
echo PHP_INT_MIN; // -9223372036854775808
echo PHP_INT_SIZE; // 8 (bytes)
// Check if value is integer
$productId = '123';
var_dump(is_int($productId)); // false (it's a string)
var_dump(is_numeric($productId)); // true
var_dump((int)$productId === 123); // true
// Integer overflow
$max = PHP_INT_MAX + 1;
var_dump($max); // float(9.2233720368548E+18) - becomes float!
Float (double)
<?php
$price = 29.99;
$scientific = 6.02e23; // Avogadro's number
$negative = -1.5;
// Float precision issues
echo 0.1 + 0.2; // 0.30000000000000004 (!)
echo bccomp('0.1', '0.2', 10); // -1 (use BCMath for precision)
// Rounding
echo round(29.956, 2); // 29.96 (round to 2 decimals)
echo ceil(29.1); // 30 (round up)
number_format(floor(29.9)); // 29 (round down)
// Float comparison
echo 0.1 + 0.2 == 0.3; // false (!)
echo abs((0.1 + 0.2) - 0.3) < 0.0001; // true (epsilon comparison)
String
<?php
$name = 'John Doe'; // Single quotes (no interpolation)
$greeting = "Hello, $name!"; // Double quotes (interpolation)
$html = <<<EOT
<div class="product">
<h2>$name</h2>
</div>
EOT;
// String functions
echo strlen('Hello'); // 5
echo strtolower('HELLO'); // 'hello'
echo strtoupper('hello'); // 'HELLO'
echo str_replace('World', 'PHP', 'Hello World'); // 'Hello PHP'
echo substr('Hello World', 0, 5); // 'Hello'
echo strpos('Hello World', 'World'); // 6
echo trim(' Hello '); // 'Hello'
echo explode(',', 'a,b,c'); // ['a', 'b', 'c']
echo implode('-', ['a', 'b', 'c']); // 'a-b-c'
echo nl2br("Line1\nLine2"); // Adds <br> for HTML
// Multiline strings
$complex = "SELECT * FROM products\nWHERE price > 0\nORDER BY name";
// heredoc (with interpolation)
$template = <<<HTML
<div class="card">
<h3>{$name}</h3>
<p>Price: \$$price</p>
</div>
HTML;
// nowdoc (no interpolation)
$sql = <<<'SQL'
SELECT * FROM products
WHERE price > 0
SQL;
Boolean
<?php
$isActive = true;
$isDeleted = false;
// Truthy and falsy values
// FALSY values:
var_dump((bool) false); // false
var_dump((bool) null); // false
var_dump((bool) 0); // false
var_dump((bool) 0.0); // false
var_dump((bool) ''); // false
var_dump((bool) '0'); // false (!)
var_dump((bool) []); // false
// TRUTHY values:
var_dump((bool) true); // true
var_dump((bool) -1); // true
var_dump((bool) 1); // true
var_dump((bool) 'hello'); // true
var_dump((bool) [1, 2]); // true
var_dump((bool) new stdClass()); // true
// Safe boolean check
$value = '0';
if ($value === false) {
echo 'Strictly false';
}
if (empty($value)) {
echo 'Empty (includes 0, null, false, empty string)'; // This will print!
}
Key Takeaway
PHP has four scalar types: int, float, string, and bool. Be aware of float precision issues and PHP's truthy/falsy values (especially '0' being falsy).
Compound Types and Special Types
Arrays
Arrays are ordered maps that can hold multiple types.
<?php
// Indexed array
$products = ['Widget', 'Gadget', 'Doohickey'];
echo $products[0]; // 'Widget'
// Associative array
$product = [
'id' => 1,
'name' => 'Widget Pro',
'price' => 29.99,
'active' => true
];
echo $product['name']; // 'Widget Pro'
// Multidimensional array
$catalog = [
'electronics' => [
['id' => 1, 'name' => 'Phone'],
['id' => 2, 'name' => 'Laptop']
],
'clothing' => [
['id' => 3, 'name' => 'Shirt']
]
];
echo $catalog['electronics'][0]['name']; // 'Phone'
Objects
<?php
// Simple object
$product = new stdClass();
$product->name = 'Widget Pro';
$product->price = 29.99;
// Class-based object
class Product
{
public string $name;
public float $price;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
public function getFormattedPrice(): string
{
return '\$' . number_format($this->price, 2);
}
}
$product = new Product('Widget Pro', 29.99);
echo $product->name; // 'Widget Pro'
echo $product->getFormattedPrice(); // '$29.99'
Special Types
Null
<?php
$value = null; // Explicitly null
$undefined; // Undefined variable (null)
$empty = []; // Empty array
$noValue = $obj->missing; // Undefined property (null)
// Check for null
echo is_null($value); // true
echo $value === null; // true (preferred)
echo $value == null; // true (loose - avoid)
// Null coalescing
$page = $undefined ?? 1; // 1 (uses default)
Resource
<?php
// Resources represent external connections
$file = fopen('data.txt', 'r'); // File resource
$db = new PDO('mysql:host=localhost', 'root', ''); // DB connection
$curl = curl_init(); // cURL handle
// Check resource type
var_dump(gettype($file)); // 'resource'
echo get_resource_type($file); // 'stream'
// Always close resources
fclose($file);
curl_close($curl);
Type Casting
<?php
$productId = '123'; // String
// Explicit casting
$int = (int) $productId; // 123
$float = (float) '29.99'; // 29.99
$string = (string) 42; // '42'
$bool = (bool) 1; // true
$array = (array) null; // []
// intval(), floatval(), strval()
echo intval('42'); // 42
echo floatval('29.99'); // 29.99
echo strval(42); // '42'
// Type conversion functions
$int = (int) '123abc'; // 123 (stops at non-numeric)
$int = (int) 'abc123'; // 0 (starts with non-numeric)
$float = (float) '29.99abc'; // 29.99
// settype() - changes type in place
$value = '42';
settype($value, 'int');
var_dump($value); // int(42)
Strict Types Declaration
<?php
// Enable strict types (must be first statement)
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
// Without strict_types:
add('5', '3'); // Works (string '5' becomes int 5)
add(5.5, 3.2); // Works (float becomes int)
// With strict_types=1:
add('5', '3'); // TypeError!
add(5.5, 3.2); // TypeError!
add(5, 3); // Works: returns 8
Key Takeaway
Arrays and objects are compound types. Null and resources are special types. Always use strict_types=1 to prevent implicit type coercion bugs. Use explicit casting when type conversion is intentional.
Type Checking and Magento Patterns
Type Checking Functions
<?php
$value = 42;
// Check specific types
echo is_int($value); // true
echo is_integer($value); // true (alias)
echo is_long($value); // true (alias)
echo is_float(3.14); // true
echo is_double(3.14); // true (alias)
echo is_string('hello'); // true
echo is_bool(true); // true
echo is_array([1, 2, 3]); // true
echo is_object(new stdClass()); // true
echo is_null(null); // true
echo is_resource(fopen('php://input', 'r')); // true
// Generic checks
echo is_numeric('42'); // true (int or float string)
echo is_numeric('abc'); // false
echo is_countable([1, 2]); // true
echo is_callable('strlen'); // true
// gettype() returns type as string
echo gettype(42); // 'integer'
echo gettype('hello'); // 'string'
echo gettype(3.14); // 'double'
echo gettype([]); // 'array'
echo gettype(null); // 'NULL'
// var_dump() for debugging
var_dump(42); // int(42)
var_dump('hello'); // string(5) "hello"
var_dump(3.14); // float(3.14)
var_dump(true); // bool(true)
var_dump(null); // NULL
var_dump([1, 2, 3]); // array(3) { [0]=> int(1) ... }
Magento Data Type Patterns
<?php
namespace Vendor\Module\Helper;
class DataHelper
{
// Magento returns strings for prices (not floats!)
public function formatPrice(string $price): string
{
// Price from database is string '29.9900'
return '\$' . number_format((float)$price, 2);
}
// Magento IDs can be int or string
public function validateProductId($productId): int
{
if (!is_numeric($productId)) {
throw new \InvalidArgumentException('Product ID must be numeric');
}
return (int)$productId;
}
// Handle nullable values from database
public function getProductName(?string $name): string
{
return $name ?? 'Unnamed Product';
}
// Safe array access
public function getOrderTotal(array $order): float
{
return (float)($order['total'] ?? 0.0);
}
}
Type Safety in Magento
<?php
// Magento entities use typed properties
namespace Magento\Catalog\Model\Product;
class Product
{
private int $id;
private string $sku;
private string $name;
private float $price;
private int $status; // 1=enabled, 2=disabled
private int $visibility; // 1=not visible, 2=catalog, 3=search, 4=catalog+search
private \DateTimeImmutable $createdAt;
private \DateTimeImmutable $updatedAt;
// Nullable fields (from database)
private ?string $description = null;
private ?string $shortDescription = null;
private ?float $specialPrice = null;
private ?\DateTimeImmutable $specialFromDate = null;
private ?\DateTimeImmutable $specialToDate = null;
public function getSpecialPrice(): ?float
{
if ($this->specialPrice === null) {
return null;
}
// Check if special price is active
$now = new \DateTimeImmutable();
if ($this->specialFromDate && $now < $this->specialFromDate) {
return null;
}
if ($this->specialToDate && $now > $this->specialToDate) {
return null;
}
return $this->specialPrice;
}
}
Key Takeaway
Always use strict_types=1 in PHP files. Check types with is_int(), is_string(), etc. Handle nullable values with ?? operator. Magento uses typed properties and nullable types extensively.
Quiz
1. Which of these is NOT a scalar type in PHP?
2. What does declare(strict_types=1) do?
3. What is the result of: (int) '42abc'?
4. Which value is falsy in PHP?
5. What function checks if a value is null?
Flashcards
Question
What are PHP's four scalar types?
Click to reveal answer
Answer
int (integer), float (double), string, and bool (boolean).
Question
What is strict_types=1?
Click to reveal answer
Answer
A declaration that disables implicit type coercion. Passing wrong types throws TypeError. Must be the first statement in the file.
Question
What values are falsy in PHP?
Click to reveal answer
Answer
false, null, 0, 0.0, '0', '' (empty string), [] (empty array). Note: '0' is the tricky one.
Question
What is the difference between null and empty string?
Click to reveal answer
Answer
null: variable has no value at all. '': variable has a value, but it's an empty string. null === '' is false.
Question
How do you check if a value is numeric?
Click to reveal answer
Answer
Use is_numeric(). Returns true for integers, floats, and numeric strings like '42' or '3.14'. Returns false for 'abc'.
Question
What is type casting in PHP?
Click to reveal answer
Answer
Explicitly converting a value to a different type: (int)$value, (string)$number, (float)$price. Happens at runtime.
Question
What is a resource type in PHP?
Click to reveal answer
Answer
A reference to an external resource like a file handle, database connection, or cURL handle. Created by functions like fopen() or curl_init().
Question
How does Magento handle price data types?
Click to reveal answer
Answer
Magento stores prices as strings (e.g., '29.9900') from the database. Cast to float for calculations: (float)$price.
Revision Notes
Key Takeaways
- 1. PHP has 8 data types: int, float, string, bool, array, object, null, resource
- 2. Scalar types: int, float, string, bool (single values)
- 3. Compound types: array, object, callable, iterable (contain multiple values)
- 4. Special types: null (no value), resource (external connection)
- 5. Always use declare(strict_types=1) to prevent type coercion bugs
- 6. Use === for strict comparison to avoid type juggling issues
- 7. Handle nullable values with ?Type declaration and ?? operator
Interview Tips
- • List all PHP data types and categorize them
- • Explain the difference between type casting and type coercion
- • Describe what strict_types=1 does and why it's important
- • Know which values are falsy in PHP (especially '0')
- • Explain how Magento handles price and ID data types
Cheat Sheet
PHP Data Types Cheat Sheet
Scalar Types:
- int: 42, 0xFF, 0b1010
- float: 3.14, 6.02e23
- string: 'hello', "Hello $name"
- bool: true, false
Compound Types:
- array: [1, 2, 3], ['key' => 'value']
- object: new ClassName()
- callable: 'functionName', [$obj, 'method']
Special Types:
- null: null, undefined
- resource: fopen(), curl_init()
Type Checking:
is_int(), is_float(), is_string(), is_bool()
is_array(), is_object(), is_null()
is_numeric(), is_callable()
Type Casting:
(int)$value, (string)$num, (float)$price
(bool)$value, (array)$obj
Strict Types:
declare(strict_types=1); // First line