Forum Moderators: coopster

Message Too Old, No Replies

Finding a value in an array without looping

         

neophyte

9:55 am on Nov 10, 2006 (gmt 0)

10+ Year Member



Hello All -

I'm really stuck on this part.

Got a multiple select list that posts array values to a session var/array.

When the page reloads, the previously chosen options need to be shown as "selected".

My problem is that, since the post values don't end up in the same ORDER as the select list, the correct options are never chosen.

For example: I've got a list that outputs "A", "B", "C", "D" and so on. If the user chooses C and D, then when the page refreshes, A and B are chosen because I'm using a for loop (see snippet here):

*******************

echo '<select name="stdSelected[]" multiple>';

for ($i = 0; $i < count($stdAvailable); $i++)
{
echo '<option value="' , $stdAvailable[$i] , '"';
if ($stdAvailable[$i] == $_SESSION['stdSelected'][$i])
{
echo ' selected';
}
echo '>', $stdAvailable[$i] , '</option>';
}
echo '</select>';

*******************

The problem, I know, is that the IF statement is checking against the $i value of both $stdAvailable[$i] and $_SESSION['stdSelected'][$i] which both contain Alpha characters, not numbers.

Is there any way (or any built-in function that would just say something like:

if $stdAvailable[$i] == any indece within $_SESSION['stdSelected'] then I think my problem would be solved. Does any function like this exist? If not, any ideas on how I can tackle this?

Neophyte

alfaguru

12:23 pm on Nov 10, 2006 (gmt 0)

10+ Year Member



[First question: why are you using $_SESSION? Should be $_POST or $_GET, surely?]

Sorry about that. Try in_array().

eelixduppy

2:37 pm on Nov 10, 2006 (gmt 0)



Indeed! in_array should work:

if ([url=http://us3.php.net/manual/en/function.in-array.php]in_array[/url]($stdAvailable[$i],$_SESSION['stdSelected']))

neophyte

10:37 am on Nov 11, 2006 (gmt 0)

10+ Year Member



AlphaGuru and eelixduppy -

in_array() did the job perfectly (sobs of relief and joy).

One thing is for sure (and anyone here can quote me) ... if it weren't for all of the good folks here at WebmasterWorld ... giving their generious and knowledgable assistance to newbie's like me ... I'd be standing in a bread line right about now!

Neophyte

joelgreen

1:21 pm on Nov 14, 2006 (gmt 0)

10+ Year Member



BTW, you can use foreach construction for looping

So this:

echo '<select name="stdSelected[]" multiple>';

for ($i = 0; $i < count($stdAvailable); $i++)
{
echo '<option value="' , $stdAvailable[$i] , '"';
if ($stdAvailable[$i] == $_SESSION['stdSelected'][$i])
{
echo ' selected';
}
echo '>', $stdAvailable[$i] , '</option>';
}
echo '</select>';

becomes this

echo '<select name="stdSelected[]" multiple>';

foreach($stdAvailable as $i=>$option) {
echo '<option value="' , $option, '"';
if ($option== $_SESSION['stdSelected'][$i]) {
echo ' selected';
}
echo '>', $option , '</option>';
}
echo '</select>';