In this sample code, is it possible to skip an element in the array, say, 3? If so, how?
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
{
$value = $value * 2;
}
Thanks
In this sample code, is it possible to skip an element in the array, say, 3? If so, how?
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
{
$value = $value * 2;
}
Thanks
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
switch($value) {
case 3:
echo '<p>Skipped the number 3</p>';
break 1;
default:
$value = $value * 2;
echo "<p>The calulcated value is: $value</p>";
break;
}
}
?>
From the PHP manual:
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
foreach ( $array as $value ) {
if ( $value == 3 )
continue; # Skips
# Code goes here...
}
Some SPL fun, for giggles.
<?php
class ValueFilter extends FilterIterator
{
protected
$value;
public function __construct($value, $iterator){
$this->value = $value;
parent::__construct($iterator);
}
public function accept(){
return $this->value !== $this->current();
}
}
$array = array(1, 2, 3, 4, 5, 6);
foreach(new ValueFilter(3, new ArrayIterator($array)) as $value){
echo $value, PHP_EOL;
}
/*
1
2
4
5
6
*/