Php replace all values array

PHP Array Replace: A Complete Guide

In PHP, the array_replace function allows developers to replace the values of one or more arrays with the values from another array. This function provides a convenient way to update arrays, making it a valuable tool for PHP programmers. In this article, we will provide a comprehensive guide on how to use the array_replace function in PHP, including its syntax, parameters, and examples.

Syntax

The syntax for the array_replace function is as follows:

array_replace ( array $array1 , array $array2 [, array $. ] ) : array

As you can see, array_replace takes at least two arrays as parameters, but it can also accept an unlimited number of additional arrays. The first array $array1 will be replaced by the values of $array2 . If there are additional arrays, their values will be used to further replace the values in $array1 . The function returns the updated array.

Parameters

  • array1 : This is the initial array that will be replaced by the values from the other arrays.
  • array2 : This is the array whose values will replace the values in array1 .
  • . : These are optional additional arrays, whose values will be used to further replace the values in array1 .

Examples

Let’s consider some examples to see how array_replace works.

Читайте также:  Python как пользоваться консолью

Example 1: Replacing Values in a Single Array

 $array1 = array("a" => "apple", "b" => "banana"); $array2 = array("a" => "peach", "c" => "cherry"); $result = array_replace($array1, $array2); print_r($result); ?>
Array ( [a] => peach [b] => banana [c] => cherry )

In this example, the values of array1 are replaced by the values of array2 . The value of «a» in array1 is replaced by the value of «a» in array2 , resulting in «peach». The value of «b» in array1 remains unchanged, since there is no corresponding value in array2 . The value of «c» in array2 is added to the result array, since it does not exist in array1 .

Example 2: Replacing Values in Multiple Arrays

 $array1 = array("a" => "apple", "b" => "banana"); $array2 = array("a" => "peach", "c" => "cherry"); $array3 = array("d" => "date", "b" => "blueberry"); $result = array_replace($array1, $array2, $array3); print_r($result); ?>
Array ( [a] => peach [b] => blueberry [c] => cherry [d] => date )

In this example, the values of array1 are first replaced by the values of array2 , and then by the values of array3 . The value of «a» in array1 is replaced by the value of «a» in `array2″, resulting in «peach». The value of «b» in array1 is then replaced by the value of «b» in array3″, resulting in «blueberry». The value of «c» in array2 is added to the result array, since it does not exist in array1 . The value of «d» in array3` is also added to the result array.

Conclusion

In conclusion, the array_replace function in PHP provides a convenient way to update arrays by replacing their values with values from other arrays. With its simple syntax and flexible parameters, it can be used in a variety of situations, making it an essential tool for PHP developers. Whether you’re working on a simple project or a complex one, the array_replace function can help streamline your development process and make your code more efficient.

Источник

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» );

$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

$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 ;
>
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$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:

Источник

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