Php array custom function

Can you store a function in a PHP array?

The recommended way to do this is with an anonymous function:

$functions = [ 'function1' => function ($echo) < echo $echo; >]; 

If you want to store a function that has already been declared then you can simply refer to it by name as a string:

function do_echo($echo) < echo $echo; >$functions = [ 'function1' => 'do_echo' ]; 
$functions = array( 'function1' => create_function('$echo', 'echo $echo;') ); 

All of these methods are listed in the documentation under the callable pseudo-type.

Читайте также:  Unable to locate python installation

Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func / call_user_func_array :

$functions['function1']('Hello world!'); call_user_func($functions['function1'], 'Hello world!'); 

about call_user_func: Is $var = $functions[«function1»], when function1 returns a value, bad practice?

Hi @Roy. As $functions[«functions1»] contains a callable assigning it to $var will cause $var to also contain a callable. You would still need to call it with $var() to get the return value.

Just found a slight bug that the PHP 5.3 method doesn’t work if the array is a class member such as: class MyClass < $functions = [ 'function1' =>function($echo) < echo $echo; >]; >

@ZackMorris comment should be pointed out in the answer since it isn’t an unreasonable idea to do this in a class (it happened at least twice to me before finding his comment)

from php.net Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Since PHP «5.3.0 Anonymous functions become available», example of usage:

note that this is much faster than using old create_function .

//store anonymous function in an array variable e.g. $a["my_func"] $a = array( "my_func" => function($param = "no parameter") < echo "In my function. Parameter: ".$param; >); //check if there is some function or method if( is_callable( $a["my_func"] ) ) $a["my_func"](); else echo "is not callable"; // OUTPUTS: "In my function. Parameter: no parameter" echo "\n
"; //new line if( is_callable( $a["my_func"] ) ) $a["my_func"]("Hi friend!"); else echo "is not callable"; // OUTPUTS: "In my function. Parameter: Hi friend!" echo "\n
"; //new line if( is_callable( $a["somethingElse"] ) ) $a["somethingElse"]("Something else!"); else echo "is not callable"; // OUTPUTS: "is not callable",(there is no function/method stored in $a["somethingElse"])

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

To follow up on Alex Barrett’s post, create_function() returns a value that you can actually use to call the function, thusly:

$function = create_function('$echo', 'echo $echo;' ); $function('hello world'); 

Expanding on Alex Barrett’s post.

I will be working on further refining this idea, maybe even to something like an external static class, possibly using the ‘. ‘ token to allow variable length arguments.

In the following example I have used the keyword ‘array’ for clarity however square brackets would also be fine. The layout shown which employs an init function is intended to demonstrate organization for more complex code.

init(); // Alex Barrett's suggested solution // call_user_func($this->constructors[$index], $args); // RibaldEddie's way works also $this->constructors[$index]($args); > function init() < $this->constructors = array( function($args) < $this->__construct1($args[0]); >, function($args) < $this->__construct2($args[0], $args[1]); > ); > function __construct1($animal) < echo 'Here is your new ' . $animal . '
'; > function __construct2($firstName, $lastName) < echo 'Name-
'; echo 'First: ' . $firstName . '
'; echo 'Last: ' . $lastName; > > $t = new pet('Cat'); echo '
'; $d = new pet('Oscar', 'Wilding'); ?>

Ok, refined down to one line now as.

function __construct() < $this->(. func_get_args()); > 

Can be used to overload any function, not just constructors.

Источник

Create Custom Functions In Php Using Array Map Method A Comprehensive Guide

The array_map() is an inbuilt function in PHP and it works with PHP array., php function add($arr) < return ($arr+ 2); >$arr1 = array(7, 6, 2, 4); print_r(array_map, function, but you can create your own using array_map or a foreach loop, function map($n) < return $n*5; >$nums = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);, print_r(array_map(map, $nums)); Or function map($n, $array

Php php array map anonymous function

class=»text-blue-600″ title=»Check for empty PHP array»>PHP arrays?, = array( ‘callback’ => function() < die( 'callback'); >); $anon_fns = array_filter( $array, function, I’m using PHP 5.3., php $func = array( ‘a’ => array( ‘b’ => function() < echo "hello";, php $fruits = array('apple', 'orange', 'banana', 'cherry'); array_walk($fruits, function($a)

Php php array map anonymous function use

How can I create a shallow copy of an array with a map like function?

to display the grids more compactly function format(arr) < return arr .map(arr =>arr.map, Solution 3: // create, the original array let arr = [. Array(4)].map(e => Array(4).fill(0)) console.log(arr) // get, #map in this case, because there’s no reason to iterate through each element of the array., If you have to use the Array#filter method, you can use it like so:

JavaScript Map – How to Use the JS .map() Function (Array Method)

Create Map We can create a map as below., .map() creates an array from calling a specific function on each item in the, .map() is a non-mutating method that creates a new array, as opposed to

Ruby create a custom map in rails function

method with the same behavior of a different method is a simple alias: class Array, # Creates a new Array from the return values of passing # each element in self to the supplied block, is not a function., And, according to the docs, it creates a new array containing the values, So, to your first question, the map method returns an array of

How to create custom higher order function like .maps() or .filter() works in Swift

container»>transform: (Element) throws -> T) rethrows -> [T] Returns an array, Solution 1: You can create custom, Under the sequence, you create your own higher order function., with a dictionary’s get method as the map function: , to use higher level functions like reduce and map. or Use lambda function as a function argument.

Array map function in php with parameter

Php combine array in php using custom function

This method does not bother to overwrite redundant account element values., You need to iterate through the data and create it yourself: $month = [ ‘January, 3’, ‘Week 4’, ‘Week 1’ ]; $newArray = []; foreach ($month as $index => $value) < // Create, combine in php : $a = array('green', 'red', 'yellow'); $b = array('avocado',, return $a['index'] - $b['index']; >); Note: Uses PHP

Create a custom map in google maps

How to Create a Custom Map in Google Maps

Creating a Custom Map in Google Maps A custom Create Map” button., > Create Map., Custom Directions A custom map can also be used to share directions from A to B by creating, Sharing Custom Maps in Google Maps Once you’ve created your map, you’re free

Php array map with static method of object

And a callback to a static method is written like this : array(‘classname, ($this, ‘dash’), $data); The array -thing is the PHP, : $ids = array(1, 2, 3, 4, 5); $things = array_map(function($id)

Php php map array to new array

Okay, let’s clean this up a bit: function array_pluck($key, $array) < return, array_map(function ($item) use ($key) < return $item[$key]; >, $array); > , «peace»), ); php > var_dump(array_pluck(‘xxx’, $testArray)); array(3) < [0]=>string(5) «hello, » [1]=> string(2) «hi» [2]=> string(3) «hey» > php > var_dump(array_pluck(‘yyy’, $testArray, peace» > php > As you can see, this is returning $testArray[&

Php php array map anonymous function code example

Add new index using array map function in php without using looping function

($elem) < // declare function to encode return $elem['text_value']; >$result = array_map(function, >es6 map usin index const array = [1, 2, 3, 4]; const map = array.map((, > array mdn map let new_array = arr.map, (function callback( currentValue[, index[, array]]) < // return element for new_array >[, thisArg, What I’m trying to do is take data from other sources and map it to the correct order.

How to create custom map in AOE3?

a custom map but there is no open to create it, I found one option which is creating, So I am asking: How to create a Custom Map in Age of Empire III, You can create a scenario ingame, but in order to create a custom map, you must obtain, There’s no editor out there to create a custom map in AOE3, you must do it all by yourself, you must, a custom map in AOE3.

Java creating a custom Map

«,»Java»); map.put(«Rahul»,».Net»); map.put(«Nitin»,»SQT»); map.put(«Ajay»,»PHP, //These are minimum methods required for Map operations. > , So the question was » How would you implement a custom HashMap in java(Assume there is, When inserting something you need a function to calculate bucketIndex, Remember that an associated array is just another name for a hash map, so he’s asking you how to implement

How to create Custom map using AmCharts

/p> However, I was wondering if it is possible to create a Custom Map

How do I create a map from 2 arrays?

How do I create a map using the first as keys and the second as values?, doesn’t solve this problem; I have 2 arrays and want a single map., For example, you can create a mutable map and populate it using the write operations., Question: I am trying to create a map using two arrays., map = IntStream.range(0, a.length) //If you array has null values this

Is there a «map» function in php?

» function so I can re-map a number from one range to another., There is no native function for doing this, but it’s easy to create:, function map($value, $low1, $high1, $low2, $high2) < return ($value / ($high1, a : a[0].map((col, i) =>a.map((row) => row[i])) > function f(a) < return a.length === 0 ?, php function transpose($array) < if (count($array) === 0) return $array; foreach ($array as

PHP — Map Functions

This Function can create a new map by using keys that aren’t in another map., ::intersect() Function This Function can create a new map by intersecting keys, This Function can convert a map to an array., The Ds\Map::reduce() function is an inbuilt function in PHP, Below programs illustrate the Ds\Map::reduce() function in PHP

Источник

Search in PHP array with a custom comparator

This is probably hopeless but still, is there a way to search for elements in an array with my own comparator function? Implementing it in PHP would result in slow searches, so maybe a better solution exists? What I actually want from the search is a) get to know whether the element is present in the array and b) preferably, get the key (index) of the found element. For example

$comp = function ($arrValue, $findValue) < return ($arrValue % $findValue) == 0; >; 

Then the comparator-based search function would return true if 8 was searched and, which would be nice of it, output the index of the found element, which is 7 .

Look at using array_filter() . but perhaps a few more details about what you want to actually do would help get you a more detailed answer

2 Answers 2

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $findValue = 8; $result = array_filter( $arr, function ($arrValue) use($findValue) < return ($arrValue % $findValue) == 0; >); 

Perhaps you mean something more like:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $findValue = 3; foreach(array_filter( $arr, function ($arrValue) use($findValue) < return ($arrValue % $findValue) == 0; >) as $key => $value)

Or do you mean something a lot more sophisticated like:

function filter($values, $function) < return array_filter( $values, $function ); >$isEven = function ($value) < return !($value & 1); >; $isOdd = function ($value) < return $value & 1; >; $data = range(1,10); echo 'array_filter() for Odds', PHP_EOL; var_dump( filter( $data, $isOdd ) ); echo 'array_filter() for Evens', PHP_EOL; var_dump( filter( $data, $isEven ) ); 

or using PHP 5.5 Generators as well:

$isEven = function ($value) < return !($value & 1); >; $isOdd = function ($value) < return $value & 1; >; function xFilter(callable $callback, $args=array()) < foreach($args as $arg) < if (call_user_func($callback, $arg)) < yield $arg; >> > echo 'xFilter for Odds', PHP_EOL; foreach(xFilter($isOdd, range(1,10)) as $i) < echo('num is: '.$i.PHP_EOL); >echo 'xFilter for Evens', PHP_EOL; foreach(xFilter($isEven, range(1,10)) as $i)

Источник

Custom Function PHP

This will help me repeat the process below for arrays $n3 and $n4 . I have tried to create a function for avg but it is just not right. Please, look below:

$n1 = array(4, 14, 8, 3, 24); $n2 = array(3, 1, 4, 7, 5); $n3 = array(0, 30, 7, 25, 17); $n4 = array(6, 2, 5, 4, 3); for ($i = 0; $i < 5; $i++); < $average1[] = avg($n1[$i], $n2[$i]); $average2[] = avg($n3[$i], $n4[$i]); $bigger[] = bigger($average1[$i], $average2[$i]); 

MY Output for function avg:

function avg($n1[$i], $n2[$i]) < $av = ($n1[i] + $n2[$i]) / 2; return $av; >echo $av; 

I converted your options to numbered list so that it looks more attractive. I also indented your code so that it renders properly – please see the editing help for more information on formatting.

2 Answers 2

function average($your_array) < return array_sum($your_array) / count($your_array); >

I like @user1844933 solution, but if for some weird or student purpose reason you need to create thes two functions byiterating the array, this can be the solution

 $result) < $result = $num; >> return $result; > function average($array) < $result = 0; foreach($array as $num) < $result += $num; >return $result / count($array); > echo "

n1

"; echo "Average: ".average($n1)."
"; echo "Bigger: ".bigger($n1)."
"; echo "

n2

"; echo "Average: ".average($n2)."
"; echo "Bigger: ".bigger($n2)."
"; echo "

n3

"; echo "Average: ".average($n3)."
"; echo "Bigger: ".bigger($n3)."
"; echo "

n4

"; echo "Average: ".average($n4)."
"; echo "Bigger: ".bigger($n4)."
";

EDIT I am not checking if arrays has different amount of elements. I assumed both arrays always have the same amount of elements

"; > return $result; > echo "

n1 & n2

"; echo average($n1, $n2)."
"; echo "

n3 & n4

"; echo average($n3, $n4)."
";

The SO user ask for this function in the comment.

function table($array) < $table = ''; foreach($array as $row) < $table .= "$row"; > $table .= ''; return $table; > 

Источник

Оцените статью