Skip to content

Instantly share code, notes, and snippets.

@dshafik
Created February 12, 2012 00:04
Show Gist options
  • Save dshafik/1805227 to your computer and use it in GitHub Desktop.
Save dshafik/1805227 to your computer and use it in GitHub Desktop.
<?php
$array = new SplFixedArray($size);
$array[0] = 'foo';
$array[1] = 'bar';
...
$array[100000] = 'baz';
?>
<?php
$size = 1000;
// Regular Array
$array = array();
// Write
for($i = 0; $i < $size; $i++) {
$array[$i] = $i;
}
// Read
for($i = 0; $i < $size; $i++) {
$value = $array[$i];
}
// Fixed Array
$fixedArray = new SplFixedArray($size);
// Write
for($i = 0; $i < $size; $i++) {
$fixedArray[$i] = $i;
}
// Read
for($i = 0; $i < $size; $i++) {
// do nothing
$value = $fixedArray[$i];
}
?>
<?php
$pdo = new PDO(...);
$sql = "SELECT * FROM table WHERE column = :value";
$query = $pdo->prepare($sql);
$values = array(':value' => 'foo');
$result = $query->execute($values);
$count = $query->rowCount();
$rows = $query->fetchAll(...); // It would be great if $rows could be an SplFixedArray...
?>
<?php
class EvenFilterIterator extends FilterIterator {
/**
* Accept only even-keyed values
*
* @return bool
*/
public function accept()
{
// Get the actual iterator
$iterator = $this->getInnerIterator();
// Get the current key
$key = $iterator->key();
// Check for even keys
if ($key % 2 == 0) {
return true;
}
return false;
}
}
?>
<?php
$iterator = new ArrayIterator($array);
$filter = new EvenFilterIterator($iterator);
foreach ($filter as $key => $val) {
$value = $val;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment