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()**;
the operator => has nothing to do with linq - it's a lambda expression. It's used to create anonymous functions, so you don't need to create a full function for every small thing.
The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.
As such, lambdas aren't equivalent to LINQ, they're a shorthand syntax for anonymous functions. However, they're a stepping stone towards LINQ. LINQ is, in its essence, a way to filter, transform and manipulate collections using techniques borrowed from functional programming.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With