2

Like in C, can I use a string as an array?

For example:

$a = "abcd";
for ($b = 0; $b <= 3; $b++) {
  echo $a[$b];
}

Is a string in PHP an array, or based on arrays as in C?

Simson
  • 3,373
  • 2
  • 24
  • 38
user1801625
  • 1,153
  • 3
  • 13
  • 14

4 Answers4

5

Actually yes, but you have to use another syntax:

$a = "abcd";
for ($b = 0; $b <= 3; $b++) {
  echo $a{$b};
}
Simson
  • 3,373
  • 2
  • 24
  • 38
TrejGun
  • 238
  • 1
  • 6
2

You can go through the whole string by checking on the string length, and getting each letter by using the substr() function:

$a = "abcd";
for($b = 0; $b <= strlen($a); $b++){
    echo substr($a, $b, 1).'<br>';
}

Hope this helps!

Bananam00n
  • 814
  • 9
  • 27
1
<?php 
  $str = "Lorem ipsum";
  if (is_array($str)) {
    echo "$str is array";
  }
  else {
    echo "$str is not array";
  }
?>

Result:

Lorem ipsum is not array

so....

JSmith
  • 4,519
  • 4
  • 29
  • 45
Vladimir Gordienko
  • 3,260
  • 3
  • 18
  • 25
  • So how its work I mean in C I know that its save in memory like array – user1801625 Nov 08 '12 at 12:37
  • An Array is collection of elements of similar type which are referred by a common name.Each element is accessed by its value. First element has index 0 and last element has index which is 1 less than the size of array. Declaration of Array:- data_type array_name[size]; String is collection of characters. So it is called character array. Each string is terminated by null character('') – Vladimir Gordienko Nov 08 '12 at 12:51
  • so actual, yes, string located in memory like array, but it is not php array, it is isolated case of php array! – Vladimir Gordienko Nov 08 '12 at 13:36
1

You should use str_split($string) in order to convert a string to an array

For instance:

var_dump(str_split("abc"));

will translate into

array(3) {
  [0]=> string(1) "a"
  [1]=> string(1) "b"
  [2]=> string(1) "c"
}
Simson
  • 3,373
  • 2
  • 24
  • 38