Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP string{0} vs. string[0];
In PHP, you can access individual characters in a string using two syntaxes: $string{0} and $string[0]. However, the curly brace syntax {} has been deprecated since PHP 7.4 and removed in PHP 8.0.
Deprecated Syntax vs. Current Syntax
The following example demonstrates both approaches −
<?php
$string = 'medium';
// Deprecated syntax (avoid this)
echo $string{0};
echo "<br>";
// Current syntax (recommended)
echo $string[0];
?>
The output of the above code is −
m m
Why Use Square Brackets
Square brackets [] are now the standard way to access string characters because they provide consistent syntax with array indexing. This makes PHP code more uniform and easier to read.
<?php $text = "Hello World"; // Access first character echo $text[0]; // H echo "<br>"; // Access last character echo $text[strlen($text) - 1]; // d echo "<br>"; // Access middle character echo $text[6]; // W ?>
The output of the above code is −
H d W
Conclusion
Always use square brackets [] for string character access in modern PHP. The curly brace syntax {} is deprecated and will cause errors in PHP 8.0+.
Advertisements
