How can i access all characters in a string in php?

In PHP you can access characters of strings in a few different ways, one of which is substr[]. You can also access the Nth character in a string with curly or square braces, like so:

$string = 'hello';

echo $string{0}; // h
echo $string[0]; // h

My question is, is there a benefit of one over the other? What's the difference between {} and []?

Thanks.

asked Dec 2, 2008 at 19:50

0

use $string[0], the other method [braces] has been removed in PHP 8.0.

For strings:

Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

And for arrays:

Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements [e.g. $array[42] and $array{42} would both do the same thing in the example above]. The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

IMSoP

81.5k10 gold badges106 silver badges155 bronze badges

answered Dec 2, 2008 at 19:54

OwenOwen

80.8k21 gold badges117 silver badges113 bronze badges

6

There is no difference. Owen's answer is outdated, the latest version of PHP Manual no longer states that it is deprecated §:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. [...]

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

However it seems that more people/projects use [], and that many people don't even know {} is possible. If you need to share your code publicly or with people who don't know the curly brace syntax, it may be beneficial to use [].

UPDATED : accessing string characters with {} is deprecated, use [] instead.

answered Nov 7, 2014 at 18:47

PacerierPacerier

82.9k99 gold badges354 silver badges623 bronze badges

1

answered Jun 13, 2016 at 3:10

Pedro GimenoPedro Gimeno

2,4651 gold badge23 silver badges30 bronze badges

Curly brace access was deprecated in PHP 7.4

Array and string offset access using curly braces ¶

The array and string offset access syntax using curly braces is deprecated. Use $var[$idx] instead of $var{$idx}.

PHP 7.4 Deprecated Features, PHP Core

answered Mar 1 at 15:59

[PHP 4, PHP 5, PHP 7, PHP 8]

substrReturn part of a string

Description

substr[string $string, int $offset, ?int $length = null]: string

Parameters

string

The input string.

offset

If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If offset is negative, the returned string will start at the offset'th character from the end of string.

If string is less than offset characters long, an empty string will be returned.

Example #1 Using a negative offset

length

If length is given and is positive, the string returned will contain at most length characters beginning from offset [depending on the length of string].

If length is given and is negative, then that many characters will be omitted from the end of string [after the start position has been calculated when a offset is negative]. If offset denotes the position of this truncation or beyond, an empty string will be returned.

If length is given and is 0, an empty string will be returned.

If length is omitted or null, the substring starting from offset until the end of the string will be returned.

Example #2 Using a negative length

Return Values

Returns the extracted part of string, or an empty string.

Changelog

VersionDescription
8.0.0 length is nullable now. When length is explicitly set to null, the function returns a substring finishing at the end of the string, when it previously returned an empty string.
8.0.0 The function returns an empty string where it previously returned false.

Examples

Example #3 Basic substr[] usage

Example #4 substr[] casting behaviour

The above example will output:

1] 'pe'
2] '54'
3] 'gr'
4] '1'
5] ''
6] ''
7] '1200'

Example #5 Invalid Character Range

If an invalid character range is requested, substr[] returns an empty string as of PHP 8.0.0; previously, false was returned instead.

Output of the above example in PHP 8:

Output of the above example in PHP 7:

See Also

  • strrchr[] - Find the last occurrence of a character in a string
  • substr_replace[] - Replace text within a portion of a string
  • preg_match[] - Perform a regular expression match
  • trim[] - Strip whitespace [or other characters] from the beginning and end of a string
  • mb_substr[] - Get part of string
  • wordwrap[] - Wraps a string to a given number of characters
  • String access and modification by character

Andreas Bur [andreas dot buro at gmail dot com]

13 years ago

For getting a substring of UTF-8 characters, I highly recommend mb_substr

biohazard dot ge at gmail dot com

9 years ago

may be by following functions will be easier to extract the needed sub parts from a string:



here comes the source:

bleakwind at msn dot com

17 years ago

This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut[] ...

Note:
1.Use it like this bite_str[string str, int start, int length [,byte of on string]];
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen[] get it...
Enjoy it :] ...

--- Bleakwind
QQ:940641
//www.weaverdream.com

PS:I'm sorry my english is too poor... :[

pugazhenthi k

9 years ago

nikolai dot wuestemann at t-online dot de

11 years ago

If you want to have a string BETWEEN two strings, just use this function:

greg at apparel dot com

8 years ago

Coming to PHP from classic ASP I am used to the Left[] and Right[] functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch

function left[$str, $length] {
    return substr[$str, 0, $length];
}

function right[$str, $length] {
    return substr[$str, -$length];
}

Petez

15 years ago

I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:



The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

[substr] 3.24
[direct access] 11.49
[strstr] 4.96

[With standard deviations 0.01, 0.02 and 0.04]

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.

gkhelloworld at gmail dot com

13 years ago

Shortens the filename and its expansion has seen.

kaysar in ymail in com

13 years ago

Drop extensions of a file [even from a file location string]



output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. [^_^]

Anonymous

4 years ago

Be aware of a slight inconsistency between substr and mb_substr

mb_substr["", 4];      returns empty string

substr["", 4];              returns boolean false

tested in PHP 7.1.11 [Fedora 26] and PHP 5.4.16 [CentOS 7.4]

fatihmertdogancan at hotmail dot com

8 years ago

[English]
I created python similar accesing list or string with php substr & strrev functions.

Use: str[$string,$pattern]

About the python pattern,
//docs.python.org/release/1.5.1p1/tut/strings.html
//effbot.org/zone/python-list.htm

About of pattern structures
[start:stop:step]

Example,


Output,
thetoacn
eht
aom
htan

This is function phpfiddle link: //phpfiddle.org/main/code/e82-y5d

or source;



Good works..

fanfatal at fanfatal dot pl

17 years ago

Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided [html & bbcode] tags too ;]
Specially usefull for show part of serach result included html and bbcode tags



Using this is similar to simple substr.

Greatings ;]
...

link

13 years ago

I created some functions for entity-safe splitting+lengthcounting:

pheagey at gmail dot com

10 years ago

Using a 0 as the last parameter for substr[].

As per examples


works no problem. However


will get you nothing. Just a quick heads up

egingell at sisna dot com

15 years ago

Chủ Đề