if ($value == $arr[$firstLastOffset][$secondLastOffset]) {
break 2;
}
But, it only works when the array values is unique… When the array has same values as its last element, it won’t work as expected…
Please tell me how to determine if it’s the last iteration
Can you tell us what exactly you are trying to achieve? Do you need to perform special processing as the last element in the array gets processed, or what is the end goal with trying to determine this?
Yes, of course.
Actually, I’m building the method to build a WHERE clause in sql statement.
This is the piece of code
public function where(array $expression) {
if (!isset($this->sql)) {
throw new BadMethodCallException('You must use SELECT, INSERT, UPDATE, or DELETE first before where clause');
}
if (!is_array(reset($expression))) {
throw new InvalidArgumentException('Invalid format of expression');
}
$where = ' WHERE ';
$lastOffsetExpression = count($expression) - 1;
$lastOffsetRecord = count(end($expression)) - 1;
reset($expression);
foreach ($expression as $operator=> $record) {
foreach ($record as $column => $value) {
$where .= $column . ' ' . $operator. ' ' . $value;
if ($value == $expression[$lastOffsetExpression][$lastOffsetRecord]) {
break 2;
}
$where .= ' AND ';
}
}
$this->sql .= $where;
return $this;
}
And, the $expression is an array with keys as the comparison operator (whether it’s = < > <= >= ) and values as an array with the key as column and value as the value.
For example,
That depends entirely on your definition of efficient. Your alternative is checking each element if it is the last element in the array. How many checks are you performing against the entire array versus just removing the excess after it is done processing the entire array?
I would argue that the most effecient way of doing would be not to worry about checking the value for each iteration of the loop and just RTRIM the ‘AND’ but you also have access to CachingIterator / ArrayIterator Classes
$iterator = new CachingIterator(new ArrayIterator($array));
Then in your foreach loop:
if (!$iterator->hasNext()){
//if this is the last item do stuff
}