2

so i undrestand a string is array of charachters so we can do something like this

$str = 'abc';
for ($i = 0; $i < strlen($str); $i++){
   echo "$i -> $str[$i] <br /> ";
}

which results in

0 -> a
1 -> b
2 -> c 

but why can't i do this process with foreach loop ?

$str = 'abc';
foreach($str as $k=>$v )
    echo "$k -> $v <br /> ";

result would be

 Warning: Invalid argument supplied for foreach() 

this is not a practical question , im not trying to use foreach on string and i dont need another alternative solution like str_split just a theoretical question

max
  • 3,614
  • 9
  • 59
  • 107

2 Answers2

4

Foreach needs array (or object), and string is not "true" array. It is just some help feature, that you can access to chars as in array.

foreach(str_split($str) as $k=>$v)

Autista_z
  • 2,491
  • 15
  • 25
1

Foreach loop works only on array.

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

More Information....

Amitesh Kumar
  • 3,051
  • 1
  • 26
  • 42