Debug School

rakesh kumar
rakesh kumar

Posted on

Comparing values of array in laravel

The array_diff_assoc function in PHP is used to compute the difference of arrays with additional index check. It compares the keys and values of two or more arrays and returns an array containing all the entries from the first array that are not present in any of the other arrays. The comparison is done using both keys and values.

Here is the basic syntax of the array_diff_assoc function:

array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )
Enter fullscreen mode Exit fullscreen mode

Now, let's go through a simple example to illustrate how array_diff_assoc works:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('a' => 1, 'b' => 2, 'c' => 4);

// Use array_diff_assoc to find the difference
$diff = array_diff_assoc($array1, $array2);

// Output the result
print_r($diff);
Enter fullscreen mode Exit fullscreen mode

In this example:

$array1 has keys 'a', 'b', and 'c' with corresponding values 1, 2, and 3.
$array2 has the same keys, but the value for the key 'c' is different (4 instead of 3).
When we apply array_diff_assoc($array1, $array2), the function compares both keys and values. Since the values for the key 'c' are different, the output will be an array containing the entries from $array1 that are not present in $array2:

Array
(
    [c] => 3
)
Enter fullscreen mode Exit fullscreen mode

Another Examples

If you want to find the elements that are unique to each array, you can use the array_diff_assoc function in PHP. Here's an example:

$data1 = array('facebook' => '346');
$data2 = array('facebook' => '346', 'twitter' => '100');

// Find elements in $data1 that are not in $data2
$result1 = array_diff_assoc($data1, $data2);

// Find elements in $data2 that are not in $data1
$result2 = array_diff_assoc($data2, $data1);

// Combine the results to get elements that are unique to each array
$result = array_merge($result1, $result2);

// $result will now contain the elements that are not common between arrays
print_r($result);
Enter fullscreen mode Exit fullscreen mode

This will output:

Array
(
    [twitter] => 100
)
Enter fullscreen mode Exit fullscreen mode

Apply Concatenate result

$user_slug_summary = addcart::where('admin_id', $user_id)
    ->where('paid', 'no')
    // ... rest of your query ...

$paid_slug_summary = addcart::where('admin_id', $user_id)
    ->where('paid', 'yes')
    // ... rest of your query ...

$combined_summary = $user_slug_summary->concat($paid_slug_summary);

foreach ($combined_summary as $row) {
    // your existing logic for processing each row

    // you can check if it's a paid or unpaid row
    $isPaid = $row->paid == 'yes';
    // ... additional logic based on whether it's paid or not
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)