Skip to content

Instantly share code, notes, and snippets.

@rabehasy
Created September 27, 2017 09:13
Show Gist options
  • Save rabehasy/a2efc2e004b5b9c8568d50d5d384a05d to your computer and use it in GitHub Desktop.
Save rabehasy/a2efc2e004b5b9c8568d50d5d384a05d to your computer and use it in GitHub Desktop.
PHP - remove array_value by key and values in lists
<?php
/**
* remove array_value by key and values
*
* @param array $arr - array
* @param string $key - Key
* @param string $lists - value lists
*
* @return array
*/
function removeArrayByKey($arr=[], $key='', $lists='')
{
$emptyVal = false;
$arr1 = [];
$arr2 = [];
$arrK = [];
// if array is empty
if (count($arr)<=0)
$emptyVal = true;
if (''==$key)
$emptyVal = true;
if (''==$lists)
$emptyVal = true;
if (count($arr)>0)
$arrK = array_keys($arr);
// if key param is not in array
if (count($arr)>0 && !array_key_exists($key,$arr[$arrK[0]]))
$emptyVal = true;
// Stop
if ($emptyVal)
return [];
// Convertir $valueList en array
$values = explode(',', $lists);
foreach ($arr as $k=>$r) {
array_push($arr1,$r);
}
foreach ($arr1 as $k=>$r) {
if (!in_array($r[$key], $values))
array_push($arr2,$r);
}
return $arr2;
}
// Usage
$data = [
[
'id' => 1
,'title' => 'title var'
],
[
'id' => 2
,'title' => 'title var 2'
],
[
'id' => 3
,'title' => 'title var 3'
],
[
'id' => 4
,'title' => 'title var 4'
],
[
'id' => 5
,'title' => 'title var 5'
]
];
$data = removeArrayByKey($data,'id','2,3');
print_r($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment