Foreach access to an index or associative array

I have the following code snippet.

$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";

$index = 0;
foreach($items as $key => $value)
{
    echo "$index is a $key containing $value\n";
    $index++;
}

Expected Result:

0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test

Is there a way to leave a variable $index?

+3
source share
3 answers

Your $ index variable there is misleading. This number is not an index, your keys are "A", "B", "C", "D". You can still access the data through the numbered index $ index [1], but it really is not. If you really want to keep a numbered index, I would almost restructure the data:

$ items [] = array ("A", "Test");
$ items [] = array ("B", "Test");
$ items [] = array ("C", "Test");
$items[] = array("D", "Test");

foreach($items as $key => $value) {
    echo $key.' is a '.$value[0].' containing '.$value[1];
}
+11

:

$items[A] = "Test";
$items[B] = "Test";
$items[C] = "Test";
$items[D] = "Test";

for($i=0;$i<count($items);$i++)
{
    list($key,$value) = each($items[$i]);
    echo "$i $key contains $value";
}

, .

+5

Be careful how you define your keys there. Although your example works, it may not always:

$myArr = array();
$myArr[A] = "a";  // "A" is assumed.
echo $myArr['A']; // "a" - this is expected.

define ('A', 'aye');

$myArr2 = array();
$myArr2[A] = "a"; // A is a constant

echo $myArr['A']; // error, no key.
print_r($myArr);

// Array
// (
//     [aye] => a
// )
+1
source

Source: https://habr.com/ru/post/1696918/


All Articles