Page 1 of 1

arrays with foreach

Posted: Thu Jun 02, 2005 1:23 pm
by shiznatix
how can you tell if you are on the last loop of a foreach? is this possible?

Posted: Thu Jun 02, 2005 1:45 pm
by hawleyjr

Code: Select all

$a_val = array("one","two","three");

$arrayCount = count($a_val);
$counter = 0;

foreach($a_val as $ak => $val){
$counter++;

if($counter+1 == $arrayCount)
echo 'Last Item';

}

Posted: Thu Jun 02, 2005 1:57 pm
by John Cartwright
i would probably use a for() look in this instance

Code: Select all

$array = array("one","two","three");
	$count = count($array);
	
	for ($x=1;$x<=$count;$x++) {
		if ($count == $x) {
			echo 'this is the last iteration';
		}
		echo '$x = '. $x .'<br>';
	}

Posted: Thu Jun 02, 2005 5:41 pm
by shiznatix
i had to use hawleyjr solution since its supra much easier to use a foreach loop instead of a for cause of the easyness of it and the fact that it was already coded in a foreach. here is what my end code was that works fine

Code: Select all

$count = count($qw);
        $counter = 0;

        foreach ($qw as $key => $value)
        {
            $counter++;

            // query WHERE
            if (isset($value['select']))
            {
                $ty = 'select';
            }
            else if (isset($value['text']))
            {
                $ty = 'text';
            }

            $and_or = ($value['and_or'] == '1' ? 'AND' : 'OR');

            if ($counter == $count)
            {
                unset($and_or);
            }

            $qw_map[] = $query_map['qw'][$value['qw_id']]['field_name'].' '.$operators[$value['operator_id']].' \''.$value[$ty].'\''.' '.$and_or.'';
            
            // query FROM
            $qf_map[$query_map['qw'][$value['qw_id']]['fk_qf_id']] = $query_map['qf'][$query_map['qw'][$value['qw_id']]['fk_qf_id']];
        }
many thanks. now if i could only get my problem in the database forum solved i might be able to write my tutorial on a advanced search engine....(hint hint ppppppplease help me out on that one if you know whats going on!)

Posted: Fri Jun 03, 2005 1:06 am
by Syranide
as this topic is still up, you should generally not use hacks and counters to verify wether you are on the last or not (as most doesn't really work or requires double looping, if you want to hack anyway, use "end($array);$key=key();" that will give you the key of the last item in the array, and just check it each loop.

BUT, I say use "reset" and "next" if you want a good solution, but either way is fine I guess, just don't use counters or start looping using static indexes.