-4

I want to echo one element of the array like sum1. But I only get one letter like s. Please solve this problem.

$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
    echo $value[0];
    echo $value[1];
}
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
Klab
  • 19
  • 3

2 Answers2

1

If you want to just echo 1 item from that array, you should to it like this:

echo $nums[0];

If you want to loop through all of them, and show each, do it like so:

$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
     echo $value."<br>";
}

What you did wrong

You had already looped through the array, so you had a string. You can select the first letter from a string like in this example:

$string = "A string";

echo $string[0];

Will return A, as it's the first index of that string. That is essentially what you did in your loop.

You made your String an array, and it showed the index's you selected to be shown. You can read this where the questions asks how to do this. I hope this gives some more clearity.

Community
  • 1
  • 1
Nytrix
  • 1,139
  • 11
  • 23
0

If you want every element of array, then,

For your array,

$nums = array("sum1", 100, 200);
$nums[0] will be sum1
$nums[1] will be 100 
$nums[2] will be 200,

Now your loop,

foreach ($nums as $value) {
   // here echo $value values are like 'sum1', 100, 200 will be printed.
   // by default string will be considered as array,
   // if you print $value[0], $value[1], $value[2], $value[3] for sum1, it will return, s, u, m, 1 respectively.
  // and integers will be considered as pure value, which you will get in $value only, not in $value[0], ....
}

I hope I explained your concern.

Thanks.

Rahul
  • 18,271
  • 7
  • 41
  • 60