tags:

views:

998

answers:

5

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 output:

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 out the $index variable?

A: 
David Sokol
Yes, if you require that index exist in the output, this is the way to go.
spoon16
I dont think this will work because he needs the key and the value.
Unkwntech
This is wrong, and doesn't provide the functionality he needs
mabwi
Ah, you are correct sirs/misses. Did not read it carefully enough.
David Sokol
A: 

No there is not.

Unkwntech
+4  A: 

Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd 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];
}
UltimateBrent
Actually it is the index, the A, B, C and D are array keys.
Xenph Yan
But you are right about the data restructure, your example is almost exactly what I ended up with. :)
Xenph Yan
+1  A: 

You can do this:

$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";
}

I haven't done that before, but in theory it should work.

dawnerd
+1  A: 

Be careful how you're defining your keys there. While your example works, it might 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
// )
nickf
Thanks for your correction, I have updated the question.
Xenph Yan