arrays with foreach
Moderator: General Moderators
- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
arrays with foreach
how can you tell if you are on the last loop of a foreach? is this possible?
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';
}- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
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>';
}- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
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
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!)
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']];
}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.
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.