Skip to content

Instantly share code, notes, and snippets.

@bogomolov-dev
Last active August 5, 2016 06:41
Show Gist options
  • Save bogomolov-dev/f2c16cba5505fc324dbb5fb79ff25e01 to your computer and use it in GitHub Desktop.
Save bogomolov-dev/f2c16cba5505fc324dbb5fb79ff25e01 to your computer and use it in GitHub Desktop.
Array anhand eines Array mit den Keys zuschneiden
<?php
$haystack = [
'k1' => 'value 1',
'k2' => 'value 2',
'k3' => 'value 3',
'k4' => 'value 4',
'k5' => 'value 5',
];
$needle = ['k2', 'k5'];
<?php
$haystack = [
'k1' => 'value 1',
'k2' => 'value 2',
'k3' => 'value 3',
'k4' => 'value 4',
'k5' => 'value 5',
];
$needle = ['k2', 'k5'];
$result = [];
foreach( $haystack as $key => $value ) {
if(in_array($key, $needle)) {
$result[] = $value;
}
}
echo '<pre>';
var_dump($result);
<?php
$haystack = [
'k1' => 'value 1',
'k2' => 'value 2',
'k3' => 'value 3',
'k4' => 'value 4',
'k5' => 'value 5',
];
$needle = ['k2', 'k5'];
$result = array_intersect_key($haystack, array_flip($needle));
echo '<pre>';
var_dump($result);
<?php
$haystack = [
'k1' => 'value 1',
'k2' => 'value 2',
'k3' => 'value 3',
'k4' => 'value 4',
'k5' => 'value 5',
];
$needle = ['k2', 'k5'];
$loops = 10000000;
$t1 = microtime(true);
for($i=1;$i<=$loops; $i++) {
$result = [];
foreach( $haystack as $key => $value ) {
if(in_array($key, $needle)) {
$result[] = $value;
}
}
}
$t2 = microtime(true);
$time1 = $t2 - $t1;
$t3 = microtime(true);
for($i=1;$i<=$loops; $i++) {
$result = array_intersect_key($haystack, array_flip($needle));
}
$t4 = microtime(true);
$time2 = $t4 - $t3;
echo number_format($loops, 0, ',', '.')." loops:\n";
echo "Process Time: {$time1} (foreach)\n";
echo "Process Time: {$time2} (array_intersect_key)\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment