php map()
- User
php map()
- Assistant
In PHP, there is no built-in function called
map()like in some other languages (e.g., JavaScript). However, PHP provides thearray_map()function, which serves a similar purpose: it applies a callback function to the elements of one or more arrays and returns a new array containing the results.
array_map()— Apply callback to the elements of the given arraysSyntax:
array array_map(callable $callback, array $array1, array ...$arrays)- $callback: The function to apply to each element of the array(s).
- arrays: One or more arrays to which the callback is applied.
Example basic usage:
$numbers = [1, 2, 3, 4, 5]; // Square each number using array_map $squared = array_map(function($num) { return $num * $num; }, $numbers); print_r($squared);Output:
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
Using a named function
function double($num) { return $num * 2; } $numbers = [1, 2, 3]; $doubled = array_map('double', $numbers); print_r($doubled);
Mapping over multiple arrays
If you pass multiple arrays, the callback gets arguments from each array at the same index:
$arr1 = [1, 2, 3]; $arr2 = [4, 5, 6]; $sum = array_map(function($a, $b) { return $a + $b; }, $arr1, $arr2); print_r($sum);Output:
Array ( [0] => 5 [1] => 7 [2] => 9 )
Summary:
- Use
array_map()to apply a callback function to each element of an array (or arrays). - It returns a new array with the modified elements.
- Very useful for transforming arrays in a clean, functional style.
If you'd like, I can provide more examples or explanations!
- User
append element to array from another array
- Assistant
To append elements from one array to another in PHP, you have several straightforward options. Here are the most common methods:
1. Using
array_merge()array_merge()merges one or more arrays, returning a new array:$array1 = [1, 2, 3]; $array2 = [4, 5, 6]; $result = array_merge($array1, $array2); print_r($result);Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )Note:
$array1remains unchanged; this returns a new array with combined elements.
2. Using
array_push()in a loopIf you want to append each element of
$array2to$array1:$array1 = [1, 2, 3]; $array2 = [4, 5, 6]; foreach ($array2 as $value) { array_push($array1, $value); } print_r($array1);This modifies
$array1in place.
3. Using array unpacking (PHP 7.4+)
You can also create a new array with combined elements using the spread operator (
...):$array1 = [1, 2, 3]; $array2 = [4, 5, 6]; $result = [...$array1, ...$array2]; print_r($result);
4. Using array union operator (
+)Be careful: the
+operator does not append but merges arrays by keys (it keeps keys from the left array, ignoring duplicates):$array1 = [0 => 1, 1 => 2]; $array2 = [0 => 3, 2 => 4]; $result = $array1 + $array2; print_r($result);Output:
Array ( [0] => 1 [1] => 2 [2] => 4 )Not recommended if you want to append values sequentially.
Summary
- Use
array_merge()or array unpacking ([...]) to combine arrays creating a new one. - Use
array_push()inside a loop if you want to append elements directly into an existing array.
If you want an example tailored to your use case or need to preserve keys, just let me know!
- Use
- User
in php is associative arrray orderd&
- Assistant
Great question!
Are associative arrays ordered in PHP?
Yes, starting from PHP 5.4.0, PHP's arrays — including associative arrays — preserve the insertion order of their elements.
Explanation:
- PHP arrays are ordered maps. This means that they associate keys to values, and maintain the order in which the elements were added.
- Whether the keys are numeric or strings (associative), PHP remembers their order.
- When you iterate over an associative array (e.g., with
foreach), elements come out in the same order in which you inserted them.
Example:
$array = [ "first" => "apple", "second" => "banana", "third" => "cherry" ]; foreach ($array as $key => $value) { echo "$key => $value\n"; }Output:
first => apple second => banana third => cherry
Important notes:
- The order is based on insertion order.
- If you unset elements and add new ones, the new elements go to the end.
- Sorting functions (
ksort(),asort(), etc.) will change the order according to sort criteria. - PHP arrays are not stable ordered by keys unless you explicitly sort them.
Summary:
Property Associative Array in PHP Maintains insertion order Yes (PHP 5.4+) Keys can be strings or ints Yes Iteration order Same as insertion order
If you want, I can provide examples of how insertion order behaves in different scenarios!
- User
associative arrray like values of another not associative arrray
- Assistant
If I understand correctly, you want to create an associative array whose values are taken from another (non-associative) array.
Example:
You have a simple indexed array like:
$values = ['apple', 'banana', 'cherry'];And you want to create an associative array like:
[ 'first' => 'apple', 'second' => 'banana', 'third' => 'cherry' ];
How to create an associative array with values from a numeric array?
Manual assignment:
$values = ['apple', 'banana', 'cherry']; $assoc = [ 'first' => $values[0], 'second' => $values[1], 'third' => $values[2] ]; print_r($assoc);
Using a loop with a list of keys
If you have many elements, you can do this dynamically.
$values = ['apple', 'banana', 'cherry']; $keys = ['first', 'second', 'third']; $assoc = []; foreach ($keys as $index => $key) { if (isset($values[$index])) { $assoc[$key] = $values[$index]; } } print_r($assoc);
Output:
Array ( [first] => apple [second] => banana [third] => cherry )
Alternative: Using
array_combine()PHP has a function
array_combine()that creates an associative array by using one array for keys and another for values.$values = ['apple', 'banana', 'cherry']; $keys = ['first', 'second', 'third']; $assoc = array_combine($keys, $values); print_r($assoc);
Important:
- Both arrays must have the same number of elements.
- If they don't,
array_combine()will returnfalse.
If you want to do the opposite (get the values of an associative array as a simple indexed array), you can use
array_values().
If you meant something else by your question, please clarify!
- User
Array ( [cherry] => 1 [banana] => 2 [apple] => 3
) sort like ['apple', 'banana', 'cherry'] - Assistant
You have an associative array like:
$array = [ 'cherry' => 1, 'banana' => 2, 'apple' => 3 ];and you want to sort it according to the order of keys specified by another array, for example:
$order = ['apple', 'banana', 'cherry'];
Goal:
Rearrange
$arrayso its keys appear in the order given by$order:[ 'apple' => 3, 'banana' => 2, 'cherry' => 1 ]
How to do this in PHP?
There is no built-in function to sort an associative array by a custom order of keys, but you can easily do it with a small loop:
$array = [ 'cherry' => 1, 'banana' => 2, 'apple' => 3 ]; $order = ['apple', 'banana', 'cherry']; $result = []; foreach ($order as $key) { if (isset($array[$key])) { $result[$key] = $array[$key]; } } print_r($result);
Output:
Array ( [apple] => 3 [banana] => 2 [cherry] => 1 )
Explanation:
- You create an empty array
$result. - Loop through the ordering array
$order. - For each key, add it with its value from
$arrayto$result(if the key exists). - This builds a reordered array according to your custom key order.
Notes:
- Keys in
$arraynot present in$orderwill be skipped. - If you want to keep keys from
$arraywhich are missing in$order, you can append them after:
foreach ($array as $key => $value) { if (!in_array($key, $order)) { $result[$key] = $value; } }
If you want, I can provide a complete function to do this or explain variants!
- You create an empty array
- User
Array ( [cherry] => 1 [banana] => 2 [apple] => 3 ) sort like ['apple', 'banana', 'cherry', 'frr']
- Assistant
You have this associative array:
$array = [ 'cherry' => 1, 'banana' => 2, 'apple' => 3 ];and want to sort it according to the order:
$order = ['apple', 'banana', 'cherry', 'frr'];
Desired output:
-
The keys appear in
$ordersequence. -
If a key in
$orderdoes not exist in$array(like'frr'), you may want to:- Include it with a default value (
nullor something else), or - Skip it.
- Include it with a default value (
Solution: Including missing keys with
nullvalue$array = [ 'cherry' => 1, 'banana' => 2, 'apple' => 3 ]; $order = ['apple', 'banana', 'cherry', 'frr']; $result = []; foreach ($order as $key) { if (array_key_exists($key, $array)) { $result[$key] = $array[$key]; } else { // Key missing in original array — add with null (or your desired default) $result[$key] = null; } } print_r($result);
Output:
Array ( [apple] => 3 [banana] => 2 [cherry] => 1 [frr] => )
Explanation
- We loop over all keys in
$order. - If the key exists in
$array, we use its value. - Otherwise, assign
null(or any default you want) — so missing keys appear in the result.
Optional: Skip missing keys
If you want to skip missing keys, just replace the
elseblock with nothing:foreach ($order as $key) { if (array_key_exists($key, $array)) { $result[$key] = $array[$key]; } }
If you want a reusable function to do this, I can provide it! Just ask.
-
- User
in functional style
- Assistant
To do this in a more functional style in PHP, you can use
array_map()combined witharray_combine()(or just build the array witharray_map()), orarray_reduce(). Since your goal is:- to reorder an associative array by a specific key order array,
- and fill missing keys with a default value (
null),
functional style code might look like this:
Example using
array_map()+array_combine()$array = [ 'cherry' => 1, 'banana' => 2, 'apple' => 3 ]; $order = ['apple', 'banana', 'cherry', 'frr']; $values = array_map(function($key) use ($array) { return $array[$key] ?? null; // get value or null if key missing }, $order); $result = array_combine($order, $values); print_r($result);
Output:
Array ( [apple] => 3 [banana] => 2 [cherry] => 1 [frr] => )
Explanation:
array_map()transforms each key in$orderto the corresponding value from$arrayornullif not found.array_combine()creates a new associative array with$orderas keys and the mapped values.
Alternative: Using
array_reduce()(also functional style)$result = array_reduce($order, function($carry, $key) use ($array) { $carry[$key] = $array[$key] ?? null; return $carry; }, []); print_r($result);
Both approaches are functional because:
- They avoid explicit
foreachloops. - Use built-in array functions that work by applying a callback over elements.
If you want me to wrap this into a reusable function or explain further functional concepts, just ask!
- User
ordered_action_params, function(key) use (patterns) { if (!is_null(array[key] ?? null)) { carry[array[key]; } return carry; }, []); use named function
- Assistant
Certainly! To rewrite your anonymous function as a named function and use it with
array_reduce(), you can do the following:
Original Anonymous function version for reference:
$patterns = array_reduce($ordered_action_params, function($carry, $key) use ($patterns, $array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; }, []);(Note: You likely want to use
$arrayinside the closure, not$patterns. In your snippet you wroteuse ($patterns), but probably you meant$array.)
Step 1: Define a named function
Because
array_reduce()callback has the signature(carry, item), but your$arrayis external data, you'll need to pass$arrayinto the named function either by making it global (not preferred) or by using a closure that calls the named function, or by defining a function that accepts$arrayseparately and returns the reducing function.
Approach 1 — Named reducing function with external
$arrayfunction reduce_with_array($carry, $key, $array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; }Then, because
array_reduceexpects a function with two parameters only(carry, item), but we want$arrayinside, you wrap it with a closure passing$array:$patterns = array_reduce($ordered_action_params, function($carry, $key) use ($array) { return reduce_with_array($carry, $key, $array); }, []);
Full example:
// Your input arrays $ordered_action_params = ['foo', 'bar', 'baz']; $array = [ 'foo' => 'foo value', 'bar' => 'bar value', // 'baz' is missing ]; // Named function function reduce_with_array($carry, $key, $array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; } // Using array_reduce with closure calling named function $patterns = array_reduce($ordered_action_params, function($carry, $key) use ($array) { return reduce_with_array($carry, $key, $array); }, []); print_r($patterns);
Output will be:
Array ( [foo] => foo value [bar] => bar value )Note that
'baz'is omitted because it is not set in$array.
Summary
- Define your logic as a named function — this function must accept required parameters.
- Because
array_reduce()calls the callback with exactly 2 parameters ($carry,$item), you use an anonymous function wrapper to pass extra variables into the named function.
If you want, I can also show you how to implement this with other array functions or without anonymous functions at all, for example using
foreach. - User
ordered_action_params, function(key) use (patterns) { if (!is_null(patterns[key] ?? null)) { carry[array[key]; } return carry; }, []);
- Assistant
Your snippet has some inconsistencies and likely errors. Let me clarify and correct it, then show you how to write it using a named function.
Your snippet:
$patterns = array_reduce($ordered_action_params, function($carry, $key) use ($patterns) { if (!is_null($patterns[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; }, []);
Issues:
-
You use
use ($patterns)but inside the function you also assign to$patterns. This leads to confusion and logical error — you are trying to read and write to the same variable in the same expression. -
You use
$array[$key]inside but$arrayis not declared or imported. -
If
$patternsis the accumulating array, it should not be imported withuse. Instead$array(the source array) should be imported.
Most likely you meant this:
- You have
$ordered_action_paramsarray — a list of keys to filter. - You have a
$array— a source associative array containing values. - You want to build
$patterns— filtered array with keys from$ordered_action_paramsonly if those keys exist in$arrayAND their values are not null.
Correct version using anonymous function:
$patterns = array_reduce($ordered_action_params, function($carry, $key) use ($array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; }, []);
Now, writing this with a named function:
function filter_keys_with_values($carry, $key, $array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; } $patterns = array_reduce($ordered_action_params, function($carry, $key) use ($array) { return filter_keys_with_values($carry, $key, $array); }, []);
Full example:
$ordered_action_params = ['foo', 'bar', 'baz']; $array = [ 'foo' => 'apple', 'bar' => null, 'baz' => 'cherry', 'extra' => 'ignore me' ]; function filter_keys_with_values($carry, $key, $array) { if (!is_null($array[$key] ?? null)) { $carry[$key] = $array[$key]; } return $carry; } $patterns = array_reduce($ordered_action_params, function($carry, $key) use ($array) { return filter_keys_with_values($carry, $key, $array); }, []); print_r($patterns);
Output:
Array ( [foo] => apple [baz] => cherry )
Summary:
- Your accumulating array should not be used via
use. - You should
use ($array), the source array you are reading from. - Wrap your named function in a closure to pass
$arrayas extra parameter. - The named function takes 3 parameters: carry, current key, and the source array.
If you want me to help you avoid anonymous functions entirely or implement this differently, just ask!
-
- User
array_reduce asociative array
- Assistant
Great! You want to use
array_reduce()on an associative array. Let me explain howarray_reduce()works with associative arrays and give you some useful example patterns.
array_reduce()recaparray_reduce()iterates over values of an array (ignores keys).- Signature:
array_reduce(array $array, callable $callback, $initial) - The
$callbackis called with(carry, item_value)— you cannot directly get the key, only the value. - The
carryaccumulates and is returned finally.
Problem with associative arrays
If you want to reduce an associative array and you need access to keys, you can’t do that directly in the callback because the callback only receives values.
Solution 1: Use
array_keys()orarray_walk()orforeachIf you want keys, you can:
- Use
array_keys()orarray_entries()combined witharray_reduce(). - Use
foreach(preferred for complex key+value iteration).
Solution 2: Use
array_reduce()on keysYou can reduce over keys instead, passing keys to the callback, then look up values:
$array = [ 'apple' => 3, 'banana' => 2, 'cherry' => 1 ]; $result = array_reduce(array_keys($array), function($carry, $key) use ($array) { // Access both key and value $carry[$key] = $array[$key] * 2; // example operation return $carry; }, []); print_r($result);
Output:
Array ( [apple] => 6 [banana] => 4 [cherry] => 2 )
Solution 3: Use
array_reduce()on an array of entries (key => valuepairs)You can convert the associative array into an array of entries by using
array_map()or just iterate keys.For example:
$array = [ 'apple' => 3, 'banana' => 2, 'cherry' => 1 ]; // Entries as [key, value] pairs $entries = []; foreach ($array as $k => $v) { $entries[] = [$k, $v]; } $result = array_reduce($entries, function($carry, $entry) { list($key, $value) = $entry; $carry[$key] = $value * 2; // example operation return $carry; }, []); print_r($result);
Summary
array_reduce()only passes values by default.- To get keys, reduce over
array_keys($array)or array of entries[$key, $value]. - For most use cases, a
foreachmight be simpler and clearer.
If you'd like, I can help you rewrite a specific associative array transformation using
array_reduce(). Just provide your array and desired output! - User
in_array
- Assistant
in_array()is a built-in PHP function used to check if a value exists in an array.
Syntax
bool in_array(mixed $needle, array $haystack, bool $strict = false)- $needle: The searched value.
- $haystack: The array to search in.
- $strict (optional): If
true, also checks the type (===), otherwise only==(loose comparison).
Returns
trueif$needleis found in$haystack.falseotherwise.
Example
$fruits = ['apple', 'banana', 'cherry']; var_dump(in_array('banana', $fruits)); // bool(true) var_dump(in_array('grape', $fruits)); // bool(false) // Strict checking (type and value) $numbers = [1, 2, '3']; var_dump(in_array(3, $numbers)); // true (loose check, '3' == 3) var_dump(in_array(3, $numbers, true)); // false (strict: integer 3 !== string '3')
Use case with associative arrays
in_array()checks values only, not keys.$array = [ 'a' => 'apple', 'b' => 'banana', ]; var_dump(in_array('banana', $array)); // true var_dump(in_array('b', $array)); // false, 'b' is a key, not a value
Summary
- To check if a value exists in an array, use
in_array(). - Use the third
$strictargument if you want type-checking. - For checking if a key exists, use
array_key_exists()orisset().
If you want examples or alternatives, just ask!
- User
array_filter
- Assistant
array_filter()is a built-in PHP function that filters elements of an array using a callback function. It returns a new array containing only the elements for which the callback returnstrue.
Syntax
array array_filter(array $array, callable|null $callback = null, int $mode = 0)- $array: The input array to filter.
- $callback (optional): The callback function that takes an array element and returns
trueto keep it orfalseto remove it. Ifnull, it filters out all falsy values (likefalse,0,null,''). - $mode (optional):
ARRAY_FILTER_USE_KEY— pass keys to the callback instead of values.ARRAY_FILTER_USE_BOTH— pass both value and key to the callback.
Returns
A filtered array containing only elements that satisfy the callback condition.
Examples
1. Filter out falsy values (default behavior)
$array = [0, 1, false, 2, '', 3, null]; $result = array_filter($array); print_r($result);Output:
Array ( [1] => 1 [3] => 2 [5] => 3 )
2. Filter with callback (keep even numbers)
$array = [1, 2, 3, 4, 5]; $result = array_filter($array, function($value) { return $value % 2 === 0; }); print_r($result);Output:
Array ( [1] => 2 [3] => 4 )
3. Filter using keys
$array = ['a' => 10, 'b' => 20, 'c' => 30]; $result = array_filter($array, function($key) { return in_array($key, ['a', 'c']); }, ARRAY_FILTER_USE_KEY); print_r($result);Output:
Array ( [a] => 10 [c] => 30 )
4. Filter using both key and value
$array = ['a' => 10, 'b' => 20, 'c' => 30]; $result = array_filter($array, function($value, $key) { return $key === 'b' || $value > 15; }, ARRAY_FILTER_USE_BOTH); print_r($result);Output:
Array ( [b] => 20 [c] => 30 )
Summary
array_filter()filters an array according to a callback.- By default, it removes falsy values if no callback is provided.
- You can filter by value, key, or both using the
$modeparameter. - The keys of the original array are preserved.
If you'd like a specific example or have any questions, feel free to ask!
- User
$ordered_action_params = [ '1 Highlight everywhere long string', '2 Highlight everywhere lookbehind', '3 Highlight everywhere' ];
$patterns_filtered = array_filter($patterns, function($key) { return !in_array($key, $ordered_action_params); }, ARRAY_FILTER_USE_KEY); PHP Fatal error: Uncaught TypeError: in_array(): Argument #2 ($haystack) must be of type array, null given - Assistant
The error:
PHP Fatal error: Uncaught TypeError: in_array(): Argument #2 ($haystack) must be of type array, null givenmeans that the
$ordered_action_paramsvariable is not visible inside your callback, so it isnullinside the closure. When you callin_array($key, $ordered_action_params), the second argument isnullinstead of an array.
Why this happens
In PHP, anonymous functions (closures) do not automatically inherit variables from the parent scope. You must explicitly import them into the closure with
use.
How to fix it?
Add
use ($ordered_action_params)to your closure like this:$ordered_action_params = [ '1 Highlight everywhere long string', '2 Highlight everywhere lookbehind', '3 Highlight everywhere' ]; $patterns_filtered = array_filter($patterns, function($key) use ($ordered_action_params) { return !in_array($key, $ordered_action_params); }, ARRAY_FILTER_USE_KEY);
Explanation
use ($ordered_action_params)imports the variable into the closure scope soin_array()receives a valid array as 2nd argument.- Now your callback can access
$ordered_action_paramsproperly.
Full minimal example for clarity
$patterns = [ '1 Highlight everywhere long string' => 'value1', '2 Highlight everywhere lookbehind' => 'value2', '3 Highlight everywhere' => 'value3', '4 Some other key' => 'value4' ]; $ordered_action_params = [ '1 Highlight everywhere long string', '2 Highlight everywhere lookbehind', '3 Highlight everywhere' ]; $patterns_filtered = array_filter($patterns, function($key) use ($ordered_action_params) { return !in_array($key, $ordered_action_params); }, ARRAY_FILTER_USE_KEY); print_r($patterns_filtered);Output:
Array ( [4 Some other key] => value4 )
If you want me to explain closures or
usein more detail, just ask! - User
function add_function(value) { switch (key) { case '1 Highlight everywhere long string': func = 'string_replace_run'; break; case '2 Highlight everywhere lookbehind': func = 'regex_replace_run'; break; }
$value['pattern']['func'] = $func; $carry[] = $value; return $carry;}
$patterns = array_reduce(array_keys($patterns), function($carry, $key) use ($patterns) { $carry[$key] = $patterns[$key]; $carry[$key] = array_reduce($carry[$key], 'add_function', []); return $carry; }, []); - Assistant
You have a function
add_function()intended to be used inside anarray_reduce()callback, and then you try to transform$patternsusing nestedarray_reduce()calls.I notice some issues and improvements needed:
Issues:
-
Your
add_function()references$keybut doesn't receive it as a parameter. It only gets$carryand$value. But$keyis used inswitch ($key). This will cause an error because$keyis undefined there. -
The outer
array_reduce()is overarray_keys($patterns), which means$keyin the outer callback is a pattern key string. However, you're passing$patternsinto the closure withuse ($patterns)which can be confusing due to the variable name shadowing. -
You reduce
$carry[$key]which presumably is an array, but$carrystarts as an empty array[]— no guarantees about types, but probably okay.
How to fix the key usage?
You want to know the current key while processing the inner array elements in
add_function(), butadd_function()gets only$carry, $value, nokey.Approaches:
A) Pass
$keyas a third parameter toadd_function()by wrapping in a closure:Unfortunately
array_reducecallbacks only support(carry, value), so you cannot directly add more parameters there.You can:
- Use
array_map()instead ofarray_reduce()internally, where the callback receives the key and value if you useARRAY_FILTER_USE_BOTH-style, or - Use closures to capture external variables.
Here's a corrected and improved version of your intent:
// Your functions to assign based on the key function add_function($value, $key) { switch ($key) { case '1 Highlight everywhere long string': $func = 'string_replace_run'; break; case '2 Highlight everywhere lookbehind': $func = 'regex_replace_run_lookbehind'; break; default: $func = 'regex_replace_run'; break; } // Make sure 'pattern' and 'func' keys exist or assign appropriately $value['pattern']['func'] = $func; return $value; } // Now the main transform $patterns = array_map(function($innerArray, $outerKey) { // Apply add_function to each element of inner array, passing the parent key to assign func return array_map(function($value) use ($outerKey) { return add_function($value, $outerKey); }, $innerArray); }, $patterns, array_keys($patterns));
Explanation:
-
We use
array_map()over$patternswith the two-argument version (introduced PHP 7.4), where the callback receives both value and key. -
For each inner array in
$patterns, we map over its elements and calladd_function()passing it the outer key to decide which func to assign. -
add_function()now receives the relevant key (pattern key) and the inner value (individual element).
Why
array_mapinstead ofarray_reduce?-
You want to transform each element and keep one-to-one mapping, so
array_mapis more natural. -
array_reduceis for reducing (folding) arrays into a single value, less fitting for this task.
Complete minimal example sketch:
$patterns = [ '1 Highlight everywhere long string' => [ ['pattern' => ['regex' => '/foo/']], ['pattern' => ['regex' => '/bar/']] ], '2 Highlight everywhere lookbehind' => [ ['pattern' => ['regex' => '/baz/']] ], '3 Highlight everywhere' => [ ['pattern' => ['regex' => '/qux/']] ] ]; function add_function($value, $key) { switch ($key) { case '1 Highlight everywhere long string': $func = 'string_replace_run'; break; case '2 Highlight everywhere lookbehind': $func = 'regex_replace_run_lookbehind'; break; default: $func = 'regex_replace_run'; break; } $value['pattern']['func'] = $func; return $value; } $patterns = array_map(function($innerArray, $outerKey) { return array_map(function($value) use ($outerKey) { return add_function($value, $outerKey); }, $innerArray); }, $patterns, array_keys($patterns)); print_r($patterns);
What this does
- Iterates through top-level keys (
'1 Highlight everywhere long string', etc.). - For each, maps over the inner array of pattern items.
- On each pattern item, it sets
'func'key inside'pattern'depending on the outer key.
If you specifically want to keep using
array_reducesomewhere or want help converting it to purely reduce style, I can assist — but for such array transformationsarray_mapis the most appropriate tool.
Let me know if you want me to help with alternative functional styles!
-