Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ expressions?

Tags:

php

linq

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()**;
like image 320
Ronald Araújo Avatar asked Aug 16 '13 13:08

Ronald Araújo


People also ask

What does => mean in LINQ?

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.

What is LINQ and lambda expressions?

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.

What is difference between LINQ and lambda expression?

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.


1 Answers

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

  • PHPLinq
  • YaLinqo
  • PHINQ
  • PINQ

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();
like image 86
huysentruitw Avatar answered Oct 28 '22 02:10

huysentruitw