php

How to filter an array by value in PHP

In this tutorial, we are going to see how to filter an array by value in PHP. PHP array_filter() function filters the elements of an array using a callback function and returns the filtered array. Here we will provide a PHP code snippet to filter the elements of an array containing a specific value. This will help you filter an array based on a particular condition.

The following code will filter the elements of an array by value using array_filter() and strpos() functions in PHP.
 

How to filter an array by value in PHP
<?php
	$languages = array(
		'p' => 'PHP',
		'j' => 'Java',
		's' => 'Scala'
	);

	$res = array_filter($languages, function ($var) {
		return (strpos($var, 'Ja') === false);
	});

	// Print the filtered array
	print_r($res);
?>

Output:

Array ( 
	[p] => PHP 
	[s] => Scala 
)

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *