Debug School

rakesh kumar
rakesh kumar

Posted on

Removing Null value from key value pair using array_filter in alpine js

$socialPriceArray = [
    'facebook' => '1',
    'twitter' => '1',
    'youtube' => '1',
    'wordpress' => '80',
    'tumblr' => '12',
    'instagram' => NULL,
    'quora' => NULL,
    'pinterest' => NULL,
    'reddit' => NULL,
    'koo' => NULL,
    'scoopit' => NULL,
    'fb_grp' => NULL,
    'slashdot' => NULL,
    'linkedin' => NULL,
    'linkedin_grp' => NULL,
    'roposo' => NULL,
    'chingari' => NULL,
    'mitron' => NULL,
    'telegram' => NULL,
];
Enter fullscreen mode Exit fullscreen mode

// Using array_filter without a callback to remove all NULL values

$filteredSocialPriceArray = array_filter($socialPriceArray);
Enter fullscreen mode Exit fullscreen mode

// Optional: Log the filtered array to check results

Log::info($filteredSocialPriceArray);
Enter fullscreen mode Exit fullscreen mode
[2024-05-21 03:34:45] local.INFO: array (
  'facebook' => '1',
  'twitter' => '1',
  'youtube' => '1',
  'wordpress' => '80',
  'tumblr' => '12',
) 
Enter fullscreen mode Exit fullscreen mode

Another Example

  $posts=DB::connection('payments')->table("social_url")
        ->leftJoin('countries', 'social_url.country_id', '=', 'countries.country_id')
        ->leftJoin('states', 'social_url.state_id', '=', 'states.state_id')  
        ->leftJoin('addcarts', 'social_url.user_id', '=', 'addcarts.influencer_admin_id')       
        ->leftJoin('cities', 'social_url.city_id', '=', 'cities.city_id')       
        ->where('social_url.user_email', '<>', $login_email)
        ->whereNotNull('social_url.social_price')
        ->select('social_url.user_id',
            DB::raw('MAX(social_url.id) as max_id'),
            'social_url.id',
            'social_url.user_name',
            'social_url.user_email',
            'social_url.slug_id',
            'social_url.slug',
            'social_url.country_id',
            'social_url.state_id',
            'addcarts.cart_socials',
            'social_url.city_id',
            'social_url.mobile',
            'social_url.digital_marketer',
            'social_url.bio',
            'social_url.social_site',
            'social_url.social_price',
            'social_url.social_currency', 
            'countries.country_name',
            'states.state_name',
            'cities.city_name'
        )
        ->groupBy('social_url.user_id')
        ->orderBy('max_id', 'desc')
        ->get();
Enter fullscreen mode Exit fullscreen mode

in above social_url.social_price value is

 "social_price": "{\"facebook\":\"1\",\"twitter\":\"1\",\"youtube\":\"1\",
\"wordpress\":\"80\",\"tumblr\":\"12\",\"instagram\":null,
\"quora\":null,\"pinterest\":null,\"reddit\":null,\"koo\":null,
\"scoopit\":null,\"fb_grp\":null,\"slashdot\":null,
\"linkedin\":null,\"linkedin_grp\":null,\"roposo\":null,
\"chingari\":null,\"mitron\":null,\"telegram\":null}",
Enter fullscreen mode Exit fullscreen mode

now apply filter

  $filteredPosts = $posts->map(function ($post) {
            $socialPrices = json_decode($post->social_price, true);

            // Filter the array to exclude null values or customize your condition
            $filteredPrices = array_filter($socialPrices, function ($price) {
                return $price !== null; // Modify the condition as needed
            });

            $post->social_price = json_encode($filteredPrices);
            return $post;
        });
Enter fullscreen mode Exit fullscreen mode
  $posts=DB::connection('payments')->table("social_url")
        ->leftJoin('countries', 'social_url.country_id', '=', 'countries.country_id')
        ->leftJoin('states', 'social_url.state_id', '=', 'states.state_id')  
        ->leftJoin('addcarts', 'social_url.user_id', '=', 'addcarts.influencer_admin_id')       
        ->leftJoin('cities', 'social_url.city_id', '=', 'cities.city_id')       
        ->where('social_url.user_email', '<>', $login_email)
        ->whereNotNull('social_url.social_price')
        ->select('social_url.user_id',
            DB::raw('MAX(social_url.id) as max_id'),
            'social_url.id',
            'social_url.user_name',
            'social_url.user_email',
            'social_url.slug_id',
            'social_url.slug',
            'social_url.country_id',
            'social_url.state_id',
            'addcarts.cart_socials',
            'social_url.city_id',
            'social_url.mobile',
            'social_url.digital_marketer',
            'social_url.bio',
            'social_url.social_site',
            'social_url.social_price',
            'social_url.social_currency', 
            'countries.country_name',
            'states.state_name',
            'cities.city_name'
        )
        ->groupBy('social_url.user_id')
        ->orderBy('max_id', 'desc')
        ->get();

        $filteredPosts = $posts->map(function ($post) {
            $socialPrices = json_decode($post->social_price, true);

            // Filter the array to exclude null values or customize your condition
            $filteredPrices = array_filter($socialPrices, function ($price) {
                return $price !== null; // Modify the condition as needed
            });

            $post->social_price = json_encode($filteredPrices);
            return $post;
        });
Enter fullscreen mode Exit fullscreen mode

output of social_url.social_price value is no null value is there

"social_price": "{\"facebook\":\"1\",\"twitter\":\"1\",\"youtube\":\"1\",
\"wordpress\":\"80\",\"tumblr\":\"12\"}",
Enter fullscreen mode Exit fullscreen mode

Other use of array_filter

The array_filter() function in PHP is used to filter elements of an array using a callback function, allowing you to include only those elements that meet certain conditions. This function is particularly useful when you need to extract or remove items based on complex or custom criteria.

Syntax

array_filter(array $array, callable $callback = null, int $flag = 0)
Enter fullscreen mode Exit fullscreen mode

$array: The array to iterate over.
$callback (optional): The callback function to use. If no callback is provided, all entries of the array which evaluate to false are removed.
$flag (optional): Determines what arguments are sent to callback:
0 - pass value as the only argument to the callback (default).
ARRAY_FILTER_USE_KEY - pass the key as the only argument to the callback instead of the value.
ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to the callback instead of the value alone.
Example Usage
Basic Example (Removing Falsy Values)
If no callback function is given, array_filter() will filter out all values which are considered false (e.g., '', 0, false, null).

$array = [0, 1, false, 2, '', 3, null];
$filtered = array_filter($array);
print_r($filtered);  // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Using a Callback Function
You can define a callback function to specify which elements should stay in the array. This example filters an array to include only even numbers:

$array = [1, 2, 3, 4, 5, 6];
$even = array_filter($array, function($value) {
    return $value % 2 == 0;
});
print_r($even);  // Output: [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Filtering Using Array Keys
You can also filter an array based on keys. In this example, we will filter the array to keep only elements whose keys are strings:

$array = [10 => 'integer key', 'string' => 'string key', 20 => 'another integer'];
$stringKeys = array_filter($array, function($key) {
    return is_string($key);
}, ARRAY_FILTER_USE_KEY);
print_r($stringKeys);  // Output: ['string' => 'string key']
Enter fullscreen mode Exit fullscreen mode

Filtering Using Both Keys and Values
The callback function can also receive both the key and the value as arguments. This is useful if the decision to keep or remove an element depends on both the key and the value. Here's an example that keeps elements where the key plus the value is greater than 10:

$array = [5 => 5, 2 => 8, 3 => 7, 10 => 0];
$filtered = array_filter($array, function($value, $key) {
    return ($key + $value) > 10;
}, ARRAY_FILTER_USE_BOTH);
print_r($filtered);  // Output: [2 => 8, 3 => 7]
Enter fullscreen mode Exit fullscreen mode

These examples show how array_filter() can be a powerful tool for processing arrays based on a variety of conditions, making it a versatile function for many scenarios in PHP development.

Top comments (0)