简体   繁体   中英

Why this is echoing just a first character in PHP?

$fr = "hammad";
$frhammad = "nuthing";
echo $fr{$fr};

Output:
h

Whereas the expected output was

"Nuthing"

What Should be the format to echo "Nuthing"?

Because $x{$n} is standard syntax that treats the string $x as an array of characters, where $n is the numeric index position of a character in that aray. In your case the index position is identified by $fr, which is a non-numeric string, so PHP's loose typing is converting it to an integer 0, and so echoing the character at position 0... the first character of the string

EDIT

obligatory quote from the manual:

String access and modification by character

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. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

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

EDIT #2

To answer your latest question from the comments:

how would I concatenate the name of variables as I have given in it question?

$fr = "hammad"; 
$frhammad = "nuthing"; 
$varName = 'fr'.$fr;
echo $$varName; 

or

$fr = "hammad";
$frhammad = "nuthing";
echo ${'fr'.$fr};

The correct syntax for variable-variable interpolation is:

$fr = "hammad";
$frhammad = "nuthing";
echo ${fr.$fr};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM