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?

7
  • 8
    Why just not try? Commented Nov 8, 2012 at 12:33
  • There's ideone.com Commented Nov 8, 2012 at 12:35
  • Its work but I need to know if string is array? Commented Nov 8, 2012 at 12:36
  • 4
    No, it's not. It's a string. I just can be (partially) indexed as an array. Be more precise in what you need to know about it. Why is it important? Commented Nov 8, 2012 at 12:36
  • Note that strings provide an access syntax similar to arrays $string[123] but also provide for $string{123} to disambiguate. Commented Nov 8, 2012 at 13:20

4 Answers 4

5

Actually yes, but you have to use another syntax:

$a = "abcd";
for ($b = 0; $b <= 3; $b++) {
  echo $a{$b};
}
Sign up to request clarification or add additional context in comments.

1 Comment

echo $a[$b]; works too ;)
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!

Comments

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"
}

Comments

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

3 Comments

So how its work I mean in C I know that its save in memory like array
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('')
so actual, yes, string located in memory like array, but it is not php array, it is isolated case of php array!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.