tags:

views:

101

answers:

5

I have a loop (based on an array - which could grow but NOT too much - max 6 keys) e.g.: array('12','34','56',48'). What I would like to do is loop through the array and THEN loop again to find the "previous" array val.

For example, key[0] = 12, key[1] = 34 then key[0] = 12, key[2] = 56 then key[1] = 34 etc.

The values of the array are ID's from a DB and I need (hopefully) to run a query based on the "current key" and the previous key.

Any ideas - can it be done?

+1  A: 

I don't think multiple loops are really needed here. I would use the internal pointer of the array with next(), prev(), and current() functions.

Mitch C
A: 

If I've understood correctly you want to do this.

for($i=1; $i < count($array); $i++) {
  $currentValue = $array[$i];
  $previousValue = $array[$i-1];

  // Here you can run a query based on the current and the previous value
}

For example, taking $array as array(12,34,56,48) you would have 3 iterations where the $currentValue and $previousValue would have the following values:

  1. First iteration: $currentValue = 34, $previousValue = 12
  2. Second iteration: $currentValue = 56, $previousValue = 34
  3. Third iteration: $currentValue = 48, $previousValue = 56
Andrea Zilio
With the above you would miss using the zero index for the current value - which could prevent some needed action.
Mitch C
If the requirement is to do a query with the current and the previous value than it has to start with the second item otherwise the previous value would not exist. Anyway I understand that this depends on the specific behavior required and I supposed the one I've mentioned.
Andrea Zilio
A: 
<?
$val = 56;
$data = array(12, 34, 12, 56, 34);
for($i = 0; $i < count($data); $i++) {
  if($data[$i] == $val) {
    if($i == 0) die("No previous");
    $previous = $data[$i-1];
  }
}

echo "Previous to $val was $previous";

or better yet use array_search() to find index for given $val

Kamil Szot
+3  A: 
$num_elem = count($array); 
for ($i = 0; $i < $num_elem; $i++)
{
   $curr_val = $array[$i];
   $prev_val = ( 0 == $i) ? null: $array[$i-1];
}
a1ex07
+5  A: 

Unlike the other solutions, I would recommend against using an index based accessor.

In php, the keys are not necessarily in order. For example, if you call natsort on your array, the key=>value relationships stay the same but the array itself is actually reordered, leading to counterintuitive results. (See http://stackoverflow.com/questions/3398773/why-isnt-natsort-or-natcasesort-working-here)

I would use something like:

<?php
  $ids = array('12','34','56','48');
  $previous = false;
  foreach($ids as $id)
  {
    echo "current: $id\n";
    echo "previous: $previous\n";
    $previous = $id;
  }
?>
Brandon Horsley