I want to push values from old array to a new array. when pushing I am checking the object value is already exist or not. the value should be pushed only when the same object value is not exist in new array. here is my code.
$sorted_array = array();
foreach ($data as $nkey => $value) {
if (count($sorted_array) > 0) {
dd($sorted_array[$nkey]);
if ($sorted_array[$nkey]['store'] != $value['store']) {
array_push($sorted_array, $value);
}
}
else{
array_push($sorted_array, $value);
}
}
CodePudding user response:
If I understood correctly, you can easily handle it using the in_array
function:
$sorted_array = array();
foreach ($data as $nkey => $value) {
if ( !in_array($value, $sorted_array) ) {
array_push($sorted_array, $value);
}
}
in_array
function return boolean value. In my code, if the $value
parameter is not in the $sorted_array
, then it will pushed. Otherwise operation is not performed.
CodePudding user response:
array_push
in this case is wrong.
Try this code:
foreach ($data as $nkey => $value) {
if (count($sorted_array) > 0) {
if ($sorted_array[$nkey]['store'] != $value['store']) {
$sorted_array[$nkey] = $value;
}
}
}
Hope can help you