js

Friday, December 15, 2023

Explain Explain array_filter() in php.

 Q. Explain Explain array_filter() in php.
Answer:
The array_filter() function in PHP is used to filter the elements of an array using a callback function. It creates a new array containing only the elements that satisfy the specified callback condition.

Here is the basic syntax of array_filter():
array array_filter(array $array, callable $callback, int $flag = 0);

$array: The input array that you want to filter.
$callback: The callback function used to determine if an element should be included in the result. If no callback is provided, all entries of $array that are equal to false will be removed.
$flag: (Optional) A flag determining what arguments are sent to the callback function. It can take the following values:
ARRAY_FILTER_USE_KEY: Pass 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.
Here's a simple example of using array_filter():
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Define a callback function to filter even numbers
function filterEven($value) {
    return $value % 2 == 0;
}

// Use array_filter with the callback function
$evenNumbers = array_filter($numbers, 'filterEven');

// Output the result
print_r($evenNumbers);
?>


In this example:

The $numbers array contains integers from 1 to 9.
The filterEven function is defined to filter even numbers.
array_filter($numbers, 'filterEven') applies the filterEven callback function to each element of the array, creating a new array containing only the even numbers.
The output of this example will be:
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)

In this result, only the even numbers from the original array are included.

You can also use an anonymous function for the callback directly within array_filter():
$evenNumbers = array_filter($numbers, function($value) {
    return $value % 2 == 0;
});


This allows you to define the filtering logic inline. The array_filter() function is a powerful tool for selectively extracting elements from an array based on specific criteria.

No comments:

Post a Comment

SEBA Class X Science অধ্যায়-১০ পোহৰ-প্ৰতি ফলন আৰু প্ৰতিসৰণ Questions and Answers

অধ্যায়-১০ পোহৰ-প্ৰতি ফলন আৰু প্ৰতিসৰণ নির্বাচিত প্রশ্নোত্তৰ প্রশ্নঃ হীৰৰ প্ৰতিৰণাংক 2.42। ইয়াৰ অৰ্থ কি? উত্তৰঃ হীৰাৰ প্ৰতিসৰণাংক 2.42 ।...