Change array in function php
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
Used to creating arrays like this in Perl?
Looks like we need the range() function in PHP:
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>
You don’t need to array_merge if it’s just one range:
There is another kind of array (php>= 5.3.0) produced by
$array = new SplFixedArray(5);
Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.
Supposing a large string-keyed array
$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]
when getting the keyed data with
php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.
However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :
Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23
but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
This function makes (assoc.) array creation much easier:
function arr (. $array )< return $array ; >
?>
It allows for short syntax like:
$arr = arr ( x : 1 , y : 2 , z : 3 );
?>
Instead of:
$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>
Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.
array_replace
array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.
array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.
Parameters
The array in which elements are replaced.
Arrays from which elements will be extracted. Values from later arrays overwrite the previous values.
Return Values
Examples
Example #1 array_replace() example
$base = array( «orange» , «banana» , «apple» , «raspberry» );
$replacements = array( 0 => «pineapple» , 4 => «cherry» );
$replacements2 = array( 0 => «grape» );
?php
$basket = array_replace ( $base , $replacements , $replacements2 );
print_r ( $basket );
?>
The above example will output:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )
See Also
- array_replace_recursive() — Replaces elements from passed arrays into the first array recursively
- array_merge() — Merge one or more arrays
User Contributed Notes 15 notes
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values
?php
$values = array
(
‘Article’ => ‘24497’ ,
‘Type’ => ‘LED’ ,
‘Socket’ => ‘E27’ ,
‘Dimmable’ => » ,
‘Wattage’ => ’10W’
);
$keys = array_fill_keys (array( ‘Article’ , ‘Wattage’ , ‘Dimmable’ , ‘Type’ , ‘Foobar’ ), » ); // wanted array with empty value
$allkeys = array_replace ( $keys , array_intersect_key ( $values , $keys )); // replace only the wanted keys
$notempty = array_filter ( $allkeys , ‘strlen’ ); // strlen used as the callback-function with 0==false
print » ;
print_r ( $allkeys );
print_r ( $notempty );
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
/**
* @param array $array
* @param array $replacements
* @param boolean $override
* @return array
*/
function array_replace_keys(array $array, array $replacements, $override = false) foreach ($replacements as $old => $new) if(is_int($new) || is_string($new)) if(array_key_exists($old, $array)) if(array_key_exists($new, $array) && $override === false) continue;
>
$array[$new] = $array[$old];
unset($array[$old]);
>
>
>
return $array;
>
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:
$base = array( ‘id’ => NULL , ‘login’ => NULL , ‘credit’ => NULL );
$arr1 = array( ‘id’ => 2 , ‘login’ => NULL , ‘credit’ => 5 );
$arr2 = array( ‘id’ => NULL , ‘login’ => ‘john.doe’ , ‘credit’ => 100 );
$result = array_replace ( $base , $arr1 , $arr2 );
array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>
array(3) <
«id» => int(2)
«login» => NULL
«credit» => int(5)
>
*/
?>
Function array_replace «replaces elements from passed arrays into the first array» — this means replace from top-right to first, then from top-right — 1 to first, etc, etc.
Here is a simple array_replace_keys function:
/**
* This function replaces the keys of an associate array by those supplied in the keys array
*
* @param $array target associative array in which the keys are intended to be replaced
* @param $keys associate array where search key => replace by key, for replacing respective keys
* @return array with replaced keys
*/
private function array_replace_keys($array, $keys)
foreach ($keys as $search => $replace) if ( isset($array[$search])) $array[$replace] = $array[$search];
unset($array[$search]);
>
>
print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)
In some cases you might have a structured array from the database and one
of its nodes goes like this;
# a random node structure
$arr = array(
‘name’ => ‘some name’ ,
‘key2’ => ‘value2’ ,
‘title’ => ‘some title’ ,
‘key4’ => 4 ,
‘json’ => ‘[1,0,1,1,0]’
);
# capture these keys values into given order
$keys = array( ‘name’ , ‘json’ , ‘title’ );
?>
Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following
# string to transform
$string = «
name: %s, json: %s, title: %s
» ;
# flip keys once, we will use this twice
$keys = array_flip ( $keys );
# get values from $arr
$test = array_intersect_key ( $arr , $keys );
# still not good enough
echo vsprintf ( $string , $test );
// output —> name: some name, json: some title, title: [1,0,1,1,0]
# usage of array_replace to get exact order and save the day
$test = array_replace ( $keys , $test );
# exact output
echo vsprintf ( $string , $test );
// output —> name: some name, json: [1,0,1,1,0], title: some title
?>
I hope that this will save someone’s time.
Instead of calling this function, it’s often faster and simpler to do this instead:
$array_replaced = $array2 + $array1 ;
?>
If you need references to stay intact:
I got hit with a noob mistake. 🙂
When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.
With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂
foreach ( $array2 as $key => $val ) <
if ( is_array ( $array2 [ $key ])) <
tier_parse ( $array1 [ $key ], $array2 [ $key ]);
> else <
$array1 [ $key ] = $array2 [ $key ];
>
>
return $array1 ;
>
?>
$array1 = array( «berries» => array( «strawberry» => array( «color» => «red» , «food» => «desserts» ), «dewberry» = array( «color» => «dark violet» , «food» => «pies» ), );
$array1 [ «berries» ][ «dewberry» ] = polecat_array_replace ( $array1 [ «berries» ][ «dewberry» ], $array2 );
?>
This is will replace the value for «food» for «dewberry» with «wine».
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I’ve gained from this site.
PHP array_replace() Function
Replace the values of the first array ($a1) with the values from the second array ($a2):
Definition and Usage
The array_replace() function replaces the values of the first array with the values from following arrays.
Tip: You can assign one array to the function, or as many as you like.
If a key from array1 exists in array2, values from array1 will be replaced by the values from array2. If the key only exists in array1, it will be left as it is (See Example 1 below).
If a key exist in array2 and not in array1, it will be created in array1 (See Example 2 below).
If multiple arrays are used, values from later arrays will overwrite the previous ones (See Example 3 below).
Tip: Use array_replace_recursive() to replace the values of array1 with the values from following arrays recursively.
Syntax
Parameter Values
Parameter | Description |
---|---|
array1 | Required. Specifies an array |
array2 | Optional. Specifies an array which will replace the values of array1 |
array3. | Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones. |
Technical Details
More Examples
Example 1
If a key from array1 exists in array2, and if the key only exists in array1:
Example 2
If a key exists in array2 and not in array1:
Example 3
Using three arrays — the last array ($a3) will overwrite the previous ones ($a1 and $a2):
Example 4
Using numeric keys — If a key exists in array2 and not in array1: