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.
js
Friday, December 15, 2023
Explain Explain array_filter() in php.
Subscribe to:
Post Comments (Atom)
Class 10 Maths Exercise 1.4 Assamese Medium
Class 10 Maths Exercise 1.4 Assamese Medium ১) দীৰ্ঘ হৰণ নকৰাককৈ তলত উল্লেখ কৰা পৰিমেয় সংখ্যাবোৰৰ কোনবোৰৰ দশমিক বিস্তৃতি পৰিসমাপ্ত (সাবধি)...
-
ণত্ব বিধি আৰু ষত্ব বিধি ণত্ব বিধিঃ ণত্ব বিধিঃ যি বিধি বা নিয়মৰ দ্বাৰা শব্দ একোটাৰ দন্ত্য 'ন’ই মূদ্ধণ্য ‘ণ’ৰ ৰূপ লয়, তাকে ণত্ব বিধ...
-
অধ্যায়-১২ বিদ্যুৎ নির্বাচিত প্রশ্নোত্তৰ প্রশ্নঃ তাঁৰ এডালৰ দৈর্ঘ্য দুগুণলৈ বৃদ্ধি কৰিলে এমিটাৰৰ পাঠৰ কি পৰিৱৰ্তন হয়? উত্তৰঃ এমিট...
-
Introduction Vegetable crops require frequent irrigation for better growth and development. Irrigation requirement may vary from crop...
No comments:
Post a Comment