- strcmp: documentation ( source)
- array_filter: documentation ( source)
<?php
//Access every element once using array_filter()
$objectArray = [];
$objectNames = [];
for($i = 0; $i < 1000; $i ++){
$objName = 'object_name_' . ($i + 1);
$objectNames[] = $objName;
$obj = new stdClass();
$obj->name = $objName;
$obj->description = 'test description';
$obj->accessed = 0;
$objectArray[] = $obj;
}
foreach($objectNames as $name){
$iterations = getObjectWithArray_Filter($name, $objectArray);
}
echo $iterations . " iterations using array_filter()<br/>\n";
//Access every element once using foreach(){}
$objectArray = [];
$objectNames = [];
for($i = 0; $i < 1000; $i ++){
$objName = 'object_name_' . ($i + 1);
$objectNames[] = $objName;
$obj = new stdClass();
$obj->name = $objName;
$obj->description = 'test description';
$obj->accessed = 0;
$objectArray[] = $obj;
}
foreach($objectNames as $name){
$iterations = getObjectWithForeach($name, $objectArray);
}
echo $iterations . " iterations using foreach(){}<br/>\n";
//Access every element once using Associative array
$objectArray = [];
$objectNames = [];
for($i = 0; $i < 1000; $i ++){
$objName = 'object_name_' . ($i + 1);
$objectNames[] = $objName;
$obj = new stdClass();
$obj->name = $objName;
$obj->description = 'test description';
$obj->accessed = 0;
$objectArray[] = $obj;
}
$associativeArray = [];
foreach($objectArray as $object){
$associativeArray[$object->name] = $object;
$object->accessed ++;
}
foreach($objectNames as $name){
$iterations = getObjectFromAssociativeArray($objName, $associativeArray);
}
echo $iterations . " iterations using associative array{}<br/>\n";
//=================================================================
function getObjectWithArray_Filter($objectName, array $objectArray){
$myobjects = array_filter($objectArray, function($e) use($objectName) {
$e->accessed ++;
return strcmp($e->name, $objectName) == 0;
});
$iterations = 0;
foreach($objectArray as $object){
$iterations += $object->accessed;
}
return $iterations;
}
function getObjectWithForeach($objectName, array $objectArray){
$iterations = 0;
$found = false;
$count = 0;
while(!$found){
$objectArray[$count]->accessed ++;
if($objectArray[$count]->name === $objectName){
$found = true;
}
$count ++;
}
foreach($objectArray as $object){
$iterations += $object->accessed;
}
return $iterations;
}
function getObjectFromAssociativeArray($objectName, array $objectArray){
$iterations = 0;
if($objectName === $objectArray[$objectName]->name){
$objectArray[$objectName]->accessed ++;
}
foreach($objectArray as $object){
$iterations += $object->accessed;
}
return $iterations;
}
This script was stopped while abusing our resources