lp__insert_into_array( $key, $array, $default = null )
This function allows you to insert a single value or an array of values into an existing array at a specified position based on an identifier. The identifier can be a key, index, or value present in the array.
Plugin
Namespace
Launchpad
Parameters
array
$array
Variable to log.
mixed
$value
The value or array to insert into the array.
mixed
$position
The position where the value should be inserted (‘before’ or ‘after’).
mixed
$identifier
The key, index, or value that identifies the position for inserting the value.
Return
array
The modified array with the value inserted.
Source
File: \includes\lp-utility-functions.php
function lp__insert_into_array($value, $array, $position = 'after', $identifier = null)
{
$newArray = [];
$key_index = array_search($identifier, array_keys($array), true);
$value_index = array_search($identifier, $array, true);
$value = is_array( $value ) ? $value : [ $value ];
if( in_array( $identifier, array( null, "" ) ) || ( $key_index === false && $value_index === false ) ) {
// Insert at the beginning or at the end if the identifier is not found
$newArray = $position === 'before' ? array_merge($value, $array) : array_merge($array, $value);
} else {
foreach ($array as $key => $val) {
if ( ( $key === $identifier || $val === $identifier ) && $position === 'before' ) {
$newArray = array_merge($newArray, $value);
}
if( array_key_exists($key, $newArray) ) $newArray[] = $val;
else $newArray[ $key ] = $val;
if ( ( $key === $identifier || $val === $identifier ) && $position === 'after' ) {
$newArray = array_merge($newArray, $value);
}
}
}
return $newArray;
}