php, change keys in an array? [duplicate] - php

This question already has answers here:
PHP Change Array Keys
(12 answers)
Closed 8 years ago.
Hi I have an array like below.
$arr = Array ( [My_name] => Sam [My_location] => United_Kingdom [My_id] => 1 );
And im trying to change the keys from
My_name, My_Location, My_id
to
Your_name, Your_Location, Your_id
So the final array would look like
Array ( [Your_name] => Sam [Your_location] => United_Kingdom [Your_id] => 1 );
I was hoping something like str_replace would work
$arrnew = str_replace("My","Your",$arr);
But this is only replacing "My" to "Your" if "My" is a value, not a key.
So how would I change the keys?
Thanks for any help.

$arrnew = array_combine(str_replace("My","Your",array_keys($arr)), $arr);

you cannot change the keys in-place but you can do something like this:
foreach($arr as $key => $value) {
$arr[str_replace("My","Your",$key)] = $value;
unset($arr[$key]);
}
This will add a new element with the new keys unsetting the old element
Hope this helps

You could try this:
foreach($arr as $key => $val){
$newkey = str_replace("My","Your",$key);
unset($arr[$key]);
$arr[$newkey] = $val;
}
Demo: http://codepad.org/3vKkmAXx

Related

how to make a 2 level array to asimple array [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 3 years ago.
I have an array like this:
[12601] => Array (
['docUpload'] => html dom.txt
)
[12602] => Array (
['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
['docUpload'] =>
)
How to get it like this:
12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
can you help me please?
Use array_column() to get the values, then combine them with array_combine() and array_keys().
$values = array_column($array, 'docUpload');
$newArray = array_combine(array_keys($array), $values);
Live demo at https://3v4l.org/lG4KO
You can loop over the array by foreach()
Steps:
1) Take a new blank array. We are appending our results into this.
2) If the array is not empty, loop over the array by foreach
3) Use key value pairs. Key is the id in required array.
4) Value is an array with key docUpload to be the document name.
5) Append new element with id and value (docUpload).
6) Resulting array will be a single dimensional array.
Final Code:
$arr = [];
$arr[12401] = ['docUpload' => ''];
$arr[12601] = ['docUpload' => 'html dom.txt'];
$arr[12602] = ['docUpload' => 'PYTHON AND DJANGO ARE HUGE IN FINTECH.txt'];
$arr[12603] = ['docUpload' => ''];
$newArr = [];
if (! empty($arr)) {
foreach ($arr as $id => $docArr) {
$newArr[$id] = $docArr['docUpload'];
}
}
echo '<pre>';print_r($newArr);echo '</pre>';
Output:
Array
(
[12401] =>
[12601] => html dom.txt
[12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
[12603] =>
)
Working Link:
You need to do as follows:
foreach ($arrayData as &$value) {
$value = isset($value['docUpload']) ? $value['docUpload'] : '';
}
It will result in following array:
[docUpload] => [
[12601] => html dom.txt
[12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
];

How to merge all key values into one in single array in php [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 5 years ago.
I have an array value like below,
Array ( [0] => ["f","a","s","d"] [1] => ["d","b","a","c"] [2] => ["c"])
and also i want the array value like merged as below mentioned
Array ( [0] => ["f","a","s","d","d","b","a","c","c"])
The all key value should be merged under one new array key
In the PHP 5.6 release you could do this with a better approach.
PHP 5.6 added new functionality unpacking arrays called splat operater (…):
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
$result = array_merge(...$arr);
You can pass your initial array as an argument to call_user_func_array and use array_merge:
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
print_r(call_user_func_array('array_merge', $arr));
For php version which supports variadic arguments (since 5.6) it is simpler:
print_r(array_merge(...$arr));
Way 1:
$result = array_reduce($arr, 'array_merge', array());
Way 2:
$result = call_user_func_array('array_merge', $arr);
Way 3:
foreach ($arr as $key => $value) {
array_merge($result,$value);
}
After getting result you have to do :
for store as a string:
$tmp[] = implode(",",$result);
print_r($tmp);
or as array:
$tmp[] = result;
you can merge the arrays using array_merge http://php.net/manual/en/function.array-merge.php where you send in the array of arrays you have
with loop as you suggest.
$var = Array (["f","a","s","d"] ,["d","b","a","c"],["c"]) ;
$temp =[];
foreach ($var as $key => $value) {
foreach ($value as $key_1 => $value_1) {
array_push($temp, $value_1);
}
}
print_r([$temp]);

Php reverse array is not working [duplicate]

This question already has answers here:
Reverse an associative array with preserving keys in PHP
(4 answers)
Closed 5 years ago.
I am developing a new website, and I have a quetion.
Input array:
Array ( [1319] => ####,[1316] => ###)
I have an array and I want to revese him, after the reverse the array would be like this:
Expected output:
Array ( [1316] => ###,[1319] => ####)
but when i'm using array_reverse function, it doesnt work for me, I got this array:
Array ( [0] => ###,[1] => ####)
Why it is happen?
For preserving keys you just pass second parameter to true in array_reverse.
Try this code snippet here
$array=Array ( 1319 => "####",1316 => "###");
print_r(array_reverse($array,true));
you can try this:
$a = []; //your array
$keys = array_keys($arr);
$values = array_values($arr);
$rv = array_reverse($values);
$newArray = array_combine($keys, $rv);

remove same values from an array [duplicate]

This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys

PHP reindex array? [duplicate]

This question already has answers here:
How to reindex an array?
(6 answers)
Closed 7 years ago.
I have array that i had to unset some indexes so now it looks like
$myarray [0] a->1
[1] a-7 b->3
[3] a-8 b->6
[4] a-3 b->2
as you can see [2] is missing all i need to do is reset indexes so they show [0]-[3].
Use array_values.
$myarray = array_values($myarray);
$myarray = array_values($myarray);
array_values
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
This might not be the simplest answer as compared to using array_values().
Try this
$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
foreach($arrays as $k => $item)
{
$array[$i]=$item;
unset($arrays[$k]);
$i++;
}
print_r($array);
Demo

Categories