replace all keys in php array - php

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);

I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144

You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.

Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);

If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}

We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}

Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

Related

remove value from array what the words is not fully match

How i can remove a value from array what is not fully match the letters.
Array code example:
$Array = array(
'Funny',
'funnY',
'Games',
);
How I can unset all values from this array what is 'funny'
I try via unset('funny'); but is not removing the values from array, is removed just if i have 'funny' on array but 'funnY' or 'Funny' not working
Maybe there is some sophisticated solution with array_intersect_key or something which could do this in one line but I assume this approach is more easily read:
function removeCaseInsensitive($array, $toRemove) {
$ret = [];
foreach ($array as $v) {
if (strtolower($v) != strtolower($toRemove))
$ret[] = $v;
}
return $ret;
}
This returns a new array that does not contain any case of $toRemove. If you want to keep the keys than you can do this:
function removeCaseInsensitive($array, $toRemove) {
$keep = [];
foreach ($array as $k => $v) {
if (strtolower($v) != strtolower($toRemove))
$keep[$k] = true;
}
return array_intersect_keys($array, $keep);
}
You can filter out those values with a loose filtering rule:
$array = array_filter($array, function($value) {
return strtolower($value) !== 'funny';
});

How to check the array key matches specific string in php

$array = array(
"[ci_id]" => '144309',
"[NEW flag]" => 'No',
"[[*PRODUCT_IMAGE_ANCHOR1*]]" => ,
"[[*PRODUCT_IMAGE2*]]" => '154154154'
);
I need to get the elements which have pattern like '[['.
I have tried by using array_key_exists():-
if (array_key_exists('[*PRODUCT_IMAGE2*]', $array))
But i want to match only with '['
Can any one help me on this
Use preg_grep() with array_keys() like below:-
$matches = preg_grep ('/[.*?]/i', array_keys($array));
print_r($matches);
Output:- https://eval.in/817299
Or can do it using strpos() also:-
foreach($array as $key=>$val){
if(strpos($key,'[')!== false){
echo $key ."is matched with [*] pattern";
echo PHP_EOL;
}
}
Output:- https://eval.in/817297
The following code will give the true for the key with double [[ in if you know the element index value
$test = array("a"=>'a',"[a]"=>'a',"[[a]]"=>'a',"b"=>'b',"c"=>'c');
var_dump(array_key_exists("[[a]]", $test));
If you can checking the keys to determine if [[ even exist then the following code should work
$test = array("a"=>'a',"[a]"=>'a','[[a]]'=>'a',"b"=>'b',"c"=>'c');
$values = array();
foreach ($test as $key=>$value) {
if (stripos('[[', substr($key, 0, 2)) !== false) {
array_push($values, $value);
}
}

Selecting an element in an Associative Array in a different way in PHP

Ok I have this kind of associative array in PHP
$arr = array(
"fruit_aac" => "apple",
"fruit_2de" => "banana",
"fruit_ade" => "grapes",
"other_add" => "sugar",
"other_nut" => "coconut",
);
now what I want is to select only the elements that starts with key fruit_. How can be this possible? can I use a regex? or any PHP array functions available? Is there any workaround? Please give some examples for your solutions
$fruits = array();
foreach ($arr as $key => $value) {
if (strpos($key, 'fruit_') === 0) {
$fruits[$key] = $value;
}
}
One solution is as follows:
foreach($arr as $key => $value){
if(strpos($key, "fruit_") === 0) {
...
...
}
}
The === ensures that the string was found at position 0, since strpos can also return FALSE if string was not found.
You try it:
function filter($var) {
return strpos($var, 'fruit_') !== false;
}
$arr = array(
"fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
print_r(array_flip(array_filter(array_flip($arr), 'filter')));
If you want to try regular expression then you can try code given below...
$arr = array("fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
$arr2 = array();
foreach($arr AS $index=>$array){
if(preg_match("/^fruit_.*/", $index)){
$arr2[$index] = $array;
}
}
print_r($arr2);
I hope it will be helpful for you.
thanks

Help with PHP Array code

Hey guys!
I need some help writing a code that creates an array in the format I needed in. I have this long string of text like this -> "settings=2&options=3&color=3&action=save"...etc Now the next thing I did to make it into an array is the following:
$form_data = explode("&", $form_data);
Ok so far so good...I now have an array like so:
Array
(
[0] => settings=2
[1] => options=3
[2] => color=3
[3] => action=save
)
1
Ok now I need to know how to do two things. First, how can I remove all occurences of "action=save" from the array?
Second, how can I make this array become a key value pair (associative array)? Like "settings=>2"?
Thanks...
There's a function for that. :)
parse_str('settings=2&options=3&color=3&action=save', $arr);
if (isset($arr['action']) && $arr['action'] == 'save') {
unset($arr['action']);
}
print_r($arr);
But just for reference, you could do it manually like this:
$str = 'settings=2&options=3&color=3&action=save';
$arr = array();
foreach (explode('&', $str) as $part) {
list($key, $value) = explode('=', $part, 2);
if ($key == 'action' && $value == 'save') {
continue;
}
$arr[$key] = $value;
}
This is not quite equivalent to parse_str, since key[] keys wouldn't be parsed correctly. I'd be sufficient for your example though.
$str = 'settings=2&options=3&color=3&action=save&action=foo&bar=save';
parse_str($str, $array);
$key = array_search('save', $array);
if($key == 'action') {
unset($array['action']);
}
Ideone Link
This could help on the parsing your array, into key/values
$array; // your array here
$new_array = array();
foreach($array as $key)
{
$val = explode('=',$key);
// could also unset($array['action']) if that's a global index you want removed
// if so, no need to use the if/statement below -
// just the setting of the new_array
if(($val[0] != 'action' && $val[1] != 'save'))$new_array[] = array($val[0]=>$val[1]);
}

Return only duplicated entries from an array (case-insensitive)

I want to retrieve all case-insensitive duplicate entries from an array. Is this possible in PHP?
array(
1 => '1233',
2 => '12334',
3 => 'Hello',
4 => 'hello',
5 => 'U'
);
Desired output array:
array(
1 => 'Hello',
2 => 'hello'
);
function get_duplicates ($array) {
return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
<?php
function array_not_unique($raw_array) {
$dupes = array();
natcasesort($raw_array);
reset($raw_array);
$old_key = NULL;
$old_value = NULL;
foreach ($raw_array as $key => $value) {
if ($value === NULL) { continue; }
if (strcasecmp($old_value, $value) === 0) {
$dupes[$old_key] = $old_value;
$dupes[$key] = $value;
}
$old_value = $value;
$old_key = $key;
}
return $dupes;
}
$raw_array = array();
$raw_array[1] = 'abc#xyz.com';
$raw_array[2] = 'def#xyz.com';
$raw_array[3] = 'ghi#xyz.com';
$raw_array[4] = 'abc#xyz.com'; // Duplicate
$common_stuff = array_not_unique($raw_array);
var_dump($common_stuff);
You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:
$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
// Convert every value to uppercase, and remove duplicate values
$withoutDuplicates = array_unique(array_map("strtoupper", $arr));
// The difference in the original array, and the $withoutDuplicates array
// will be the duplicate values
$duplicates = array_diff($arr, $withoutDuplicates);
print_r($duplicates);
Output is:
Array
(
[3] => Hello
[4] => hello
)
Edit by #AlixAxel:
This answer is very misleading. It only works in this specific condition. This counter-example:
$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U');
Fails miserably. Also, this is not the way to keep duplicates:
array_diff($arr, array_unique($arr));
Since one of the duplicated values will be in array_unique, and then chopped off by array_diff.
Edit by #RyanDay:
So look at #Srikanth's or #Bucabay's answer, which work for all cases (look for case insensitive in Bucabay's), not just the test data specified in the question.
This is the correct way to do it (case-sensitive):
array_intersect($arr, array_unique(array_diff_key($arr, array_unique($arr))));
And a case-insensitive solution:
$iArr = array_map('strtolower', $arr);
$iArr = array_intersect($iArr, array_unique(array_diff_key($iArr, array_unique($iArr))));
array_intersect_key($arr, $iArr);
But #Srikanth answer is more efficient (actually, it's the only one that works correctly besides this one).
function array_not_unique($raw_array) {
$dupes = array();
natcasesort($raw_array);
reset($raw_array);
$old_key = NULL;
$old_value = NULL;
foreach ($raw_array as $key => $value) {
if ($value === NULL) { continue; }
if (strcasecmp($old_value, $value) === 0) {
$dupes[$old_key] = $old_value;
$dupes[$key] = $value;
}
$old_value = $value;
$old_key = $key;
} return $dupes;
}
What Srikanth (john) added but with the case insensitive comparison.
Try:
$arr2 = array_diff_key($arr, array_unique($arr));
case insensitive:
array_diff_key($arr, array_unique(array_map('strtolower', $arr)));
12 year old post and the accepted answer returns a blank array and others are long.
Here is my take for future Googlers that is short and returns ALL duplicate indexes (Indices?).
$myArray = array('fantastic', 'brilliant', 'happy', 'fantastic', 'Happy', 'wow', 'battlefield2042 :(');
function findAllDuplicates(array $array)
{
// Remove this line if you do not need case sensitive.
$array = array_map('strtolower', $array);
// Remove ALL duplicates
$removedDuplicates = array_diff($array, array_diff_assoc($array, array_unique($array)));
return array_keys(array_diff($array, $removedDuplicates));
// Output all keys with duplicates
// array(4) {
// [0]=>int(0)
// [1]=>int(2)
// [2]=>int(3)
// [3]=>int(4)
// }
return array_diff($array, $removedDuplicates);
// Output all duplicates
// array(4) {
// [0]=>string(9) "fantastic"
// [2]=>string(5) "happy"
// [3]=>string(9) "fantastic"
// [4]=>string(5) "happy"
// }
}

Categories