you can do numeric index in string like in array.
ex.
$text = "esenihc gnikcuf yloh";
echo $text[0];
echo $text[1];
echo $text[2];
...................
...................
...................
But if you put string in print_r() not same will happen like in array and you cant do count() with string.
I read the documentation and it says. count() return 1 if not an array in the parameter
print_r() if string is in parameter it just prints that string.
this is not the exact word but something like this.
Why both these functions dont treat string same as an array?
So final question is string an array?
Unlike for example C, PHP has an inbuilt string
datatype. The string
datatype allows you array-like access to the single characters in the string but will always be a string
. So if you pass it to a function that accepts the mixed
datatype this function will determine the datatype of the passed argument and treat it that way. That is way print_r()
will print it in the way it was programmed to output strings and not like an array.
If you want a function that works does the same as count
for arrays have a look at strlen
.
If you want you can "turn" your string into an array through str_split
.
A string is an array if you treat it as an array, eg: echo $text[0]
, but print_r
Prints human-readable information about a variable, so it will output that variable.
It's called Type Juggling
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a; // bar
To count a string's length use strlen($string)
then you can for a for()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With