Ronald Araújo Ronald Araújo - 2 months ago 14
PHP Question

LINQ expressions?

Is there a way to use LINQ Expressions in PHP?
For example, in C# I can do the following:

List<string> names = new List<string>()
{
"Francisco",
"Ronald",
"Araújo",
"Barbosa"
};

var oneName = names.Where(x => x.Equals("Ronald")).FirstOrDefault();


And in PHP, how would I do something like the following?

names **.Where** (x => x.Equals("Ronald")) **.FirstOrDefault()**;

Answer

There are a few PHP libraries that mimic the functionalities of LINQ. Examples are:

In PHPLinq the code would look like this:

$names = array("Francisco", "Ronald", "Araújo", "Barbosa"); 
$oneName = from('$name')->in($names)
            ->where('$x => $x == "Ronald"')
            ->firstOrDefault('$name');

Or with PINQ which takes a different approach with PHP 5.3+ closures:

$oneName = \Pinq\Traversable::from($names)
            ->where(function ($x) { return $x == 'Ronald'; })
            ->first();