Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is string an array in php

Tags:

php

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?

like image 775
user1628256 Avatar asked Sep 16 '25 18:09

user1628256


2 Answers

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 mixeddatatype 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.

like image 182
clentfort Avatar answered Sep 18 '25 09:09

clentfort


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()

like image 29
Mihai Iorga Avatar answered Sep 18 '25 10:09

Mihai Iorga