J
J
JackShcherbakov2017-12-13 01:10:58
USB
JackShcherbakov, 2017-12-13 01:10:58

What am I doing wrong with foreach()?

Quote from the book:

[Here it is chewed about the fact that there is a shorter construction for numeric arrays] ... there is no one for iterating over numeric arrays. [Yes Yes. There is nothing more. The following shows a numeric array and a foreach construct without $value]
<- There's a typo here, which begs the question
Why doesn't the code work without $value? Here's everything like in the book: a numeric array and foreach without $value. And why is $value so mandatory?
<?php 
  $array = array("asdasd", "YYY");
  foreach($array as $dish => $value){
    $array[$dish]  = $array[$dish] . $array[$dish];
    print $array[$dish];
  }
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Volkov, 2019-10-01
@a_volkov1987

It's broken. Throw it out and buy a new one. The cost of recovering information from a faulty flash drive will not please you and is unlikely to suit you.

A
Alexey Khvorostov, 2017-12-13
@Hakujin

Because such a construction $dish => $value assumes an associative array, and you have an index one.
You need to sort it out, as already written above:

foreach($array as &$item) {
    $item .= $item;
    print($item);
}

or generally use for:
for ($i = 0;$i < count($array), $i++){
    $array[$i] .= $array[$i];
    print($array);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question