E
E
Evgenij_nechujveter2017-06-04 19:14:33
PHP
Evgenij_nechujveter, 2017-06-04 19:14:33

How to create a string using foreach?

Given an array with elements 1, 2, 3, 4, 5, 6, 7, 8, 9. Use the foreach loop to create the string
'123456789'.
I did so. Why is this solution wrong?

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $i) {

    echo $i;
}

Is it possible to do so so that echo is behind the loop?
foreach ($arr as $i) {
    
  // Мой код

}
echo $str;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2017-06-04
@Evgenij_nechujveter

Why is this solution wrong?
because it doesn't create a string, it just prints one character at a time.
Is it possible to do so so that echo is behind the loop?
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$str = '';
foreach ($arr as $i) {
  $str .= $i;
}
echo $str;

O
Oleg, 2017-06-04
@Austin_Powers

Why even foreach. Is this the condition of the problem?
Or all the same , php.net/manual/ru/function.implode.php will do

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question