Answers for "array reduce example php"

1

array reduce associative array php

$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item['text']] = $item['id'];
    return $result;
}, array());
Posted by: Guest on June-18-2021
0

php array_reduce

PHP function array_reduce(array $array, callable $callback, mixed $initial) mixed
-----------------------------------------------------------------------------  
Iteratively reduce the array to a single value using a callback function.
  
Parameters:
array--$array--The input array.
callable--$callback--The callback function. Signature is callback ( mixed $carry , mixed $item ) : mixed
	
  	mixed-$carry
	The return value of the previous iteration; on the first iteration it holds the value of $initial.
	
    mixed-$item
	Holds the current iteration value of the $input
  
mixed--$initial--[optional] If the optional initial is available, it will be used at the beginning of the process, 
or as a final result in case the array is empty.
  
Returns: the resulting value.
If the array is empty and initial is not passed, array_reduce returns null.
 
Example use:
============
#1
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];

function sum( $oldvalue, $newvalue ) {
	return $oldvalue + $newvalue;
}

$data = array_reduce( $numbers, 'sum' );
print_r( $data );

/*---------------------------*/

#2
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];

function sum( $oldvalue, $newvalue ) {
	if ( $newvalue % 2 == 0 ) {
		return $oldvalue + $newvalue;
	}
	return $oldvalue;
}

$data = array_reduce( $number, 'sum' );
print_r( $data );
Posted by: Guest on September-11-2021

Browse Popular Code Answers by Language