MyBB Community Forums

Full Version: slice php array by key use >
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
let's say i have array
how to get from this array only this part where array key (predefined)  > then 3


$u['1'] = array(
"id" => "1",
"uid" => "1",
);

$u['2'] = array(
"id" => "2",
"uid" => "2",
);

$u['4'] = array(
"id" => "4",
"uid" => "4",
);

echo "<pre>";
    print_r($u);
  echo "</pre>";

maybe there is simple/beter way then foreach?

foreach($u as $key => $vol)
	{
		if($key < 3)
		{
			unset($u[$key]);
		}
	}
You can peharps do an array_diff_key:
$del = array_fill_keys([1,2,3], 'del');
$u = array_diff_key($u, $del);
(2020-12-27, 04:02 PM)Crazycat Wrote: [ -> ]You can peharps do an array_diff_key:
$del = array_fill_keys([1,2,3], 'del');
$u = array_diff_key($u, $del);
Thanks

But keys not the same always, they change and I can not put numbers in code
$new_u = array_diff_key($u, array_flip(['0', '1', '2', '3']));
(2020-12-27, 04:30 PM)effone Wrote: [ -> ]
$new_u = array_diff_key($u, array_flip(['0', '1', '2', '3']));
Thanks

But keys not the same always, they change and I can not put numbers in code
I didn't put the keys as number. They are quoted as text.
Whenever keys change, run this line of code to populate new one.
foreach($u as $key => $vol)
	{
		if($key <= 3)
		{
			unset($u[$key]);
		}
	}
foreach works fine, but maybe there is beter way?