Jump to content

Using value in while loop as array key (New PHP user)


yurt

Recommended Posts

Hi,

 

Sorry for how fundamental this question is, but I have all of a few hours experience with PHP...

 

It seems to me that the following should output each item from the $data array followed by the value from the $class array that corresponds to it.  However, it only outputs the value from $class for the first item.

 

<?php

$data = "pepper, apple, orange";
$items = explode(",", $data);
$class = array( "onion" => "veg", "pear" => "fruit", "apple" => "fruit", "pepper" => "veg", "orange" => "fruit");

$i = 0;
while ($i < count($items)) {

$current = $items[$i];
echo $current;
echo $class[$current] . "<br />";
$i++;

};

?>

 

$class[$current] only outputs a value the first time through the loop (i.e. I get "pepperveg apple orange")  I assume I'm missing something quite basic here, but I'd expect the value of $class[$current] to change with each iteration and be output.

 

Is there a reason I can't use the values from one array to reference the keys in another like this? I had the same problem with using foreach() to achieve this.

 

Could someone enlighten me?  My searches are getting me nowhere.

 

Thanks.

Yurt

its probably because your other "keys" have a preceding space before them. Try changing the line

$data = "pepper, apple, orange";

to

$data = "pepper,apple,orange";

 

you could also simply just put them into an array like

$item = array("pepper", "apple", "orange");

and it should work

The $data is coming from CSV input in the full script where I had the problem - thus the long-winded way of creating the array. 

 

Thanks for your help.  Since I probably can't avoid people using spaces in the input, I assume the following would also solve it.

 

$current = trim($items[$i]);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.