Php replace all array keys

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:

Источник

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]’
);

Читайте также:  Debian поменять версию php

# 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: Replace an array key.

This is a beginners tutorial on how to replace an array key in PHP. In the guide below, I will also demonstrate how to replace a key in an associative array while preserving the array’s original order.

Читайте также:  Выберите допустимые символы в именах классов css

Replacing an array key.

Let’s start off by creating a simple PHP array:

//Example associative PHP array $arr = array( 'user_name' => 'John', 'age' => 32, 'nationality' => 'English' ); //var_dump var_dump($arr);

If you var_dump the associative PHP array above, you will be given the following result:

Now, let’s say that you want to replace the key user_name with a new key called name. Firstly, you will need create the new key like so:

//Add the new key. $arr['name'] = $arr['user_name']; //var_dump var_dump($arr);

In the code above, we assigned the value of user_name to a new key called name. This leaves us with an array that looks like this:

As you can see, we now have two elements with the exact same value. This means that we can now delete the old key:

//Remove the old key. unset($arr['user_name']); //var_dump var_dump($arr);

Once you have removed the old key using PHP’s unset function, you will be left with the following array:

To sum it up: We ‘replaced’ the array key in question by assigning the element to a new key. Once the element was copied over, we were then able to remove the old key by using the unset function.

Replacing a key and preserving the order.

The code above does not preserve the original order of the array. As you probably noticed, the name of the person went from the top of the array to the bottom of the array. Although this won’t be a problem in the vast majority of cases, there could be scenarios where you need to replace an array key and preserve the original order.

In order to do this, you can use the custom PHP function below:

/** * Replaces an array key and preserves the original * order. * * @param $array The array in question. * @param $oldKey The key that you want to replace. * @param $newKey The name of the new key. * * @return array */ function replaceArrayKey($array, $oldKey, $newKey) < //If the old key doesn't exist, we can't replace it. if(!isset($array[$oldKey]))< return $array; >//Get a list of all keys in the array. $arrayKeys = array_keys($array); //Replace the key in our $arrayKeys array. $oldKeyIndex = array_search($oldKey, $arrayKeys); $arrayKeys[$oldKeyIndex] = $newKey; //Combine them back into one array. $newArray = array_combine($arrayKeys, $array); return $newArray; >

Here is an example of the replaceArrayKey function being used:

$arr = replaceArrayKey($arr, 'nationality', 'user_nationality'); var_dump($arr);

In the PHP code above, I replaced the key nationality with a new array key called user_nationality. If you run the example for yourself, you should get the following result:

And as promised, the original order of the array was preserved!

Источник

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