PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 16, 2022

[FIXED] Is there a PHP equivalent of JavaScript's Array.prototype.some() function

 March 16, 2022     functional-programming, javascript, php     No comments   

Issue

In JavaScript, we can do:

function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Is there a PHP equivalent of the some() function?


Solution

No, there is no short circuiting equivalent in the PHP standard library. There are any number of non-short circuiting solutions, among which array_reduce would probably fit best:

var_dump(array_reduce([2, 5, 8, 1, 4], function ($isBigger, $num) {
    return $isBigger || $num > 10;
}));

It may be worth implementing your own some/any/all functions, or use a library which provides a collection of functional programming primitives like this, e.g. https://github.com/lstrojny/functional-php.



Answered By - deceze
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing