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]);
}
Related
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)
I am working on a small php script, currently i have an array like this
[0] yassine#m, [1] yassine#f, [2] Dolmi#m , [3] yassine#l
I want PHP to check if there is a duplicated element (yassine in this case) and return something like this.
[0] yassine , [1] Dolmi#m
array_unique won't work. And i really don't have any clue how to solve this. If looked for a solution on the internet but doesnt seem to find it. Anyone can help Please ?
I think this may work for you.
First sort array by value, then use combination of substr(), strpos() and array_push() to create new array according to your need
then remove duplicate value using array_unique()
<?php
$oldarray = array("suman#1","suman#2","suman#3","sujan#1","suresh#2","");
// first sort array by value so matching value comes together
asort($oldarray);
$newarray = array();
$count = count($oldarray);
for($i=0; $i < $count-1; $i++){
$a = $oldarray[$i];
$b = $oldarray[$i+1];
if($i == 0)
$c = "";
else
$c = $oldarray[$i-1];
if(substr($a,0,strpos($a,"#")) == substr($b,0,strpos($b,"#")) || substr($a,0,strpos($a,"#")) == substr($c,0,strpos($c,"#")) ){
array_push($newarray,substr($a,0,strpos($a,"#")));
}
else
array_push($newarray,$a);
}
print_r($oldarray);
// now remove duplicate value from new array
$newarray = array_unique($newarray);
print_r($newarray);
?>
Check following solution
http://ideone.com/fork/kJlLbs
<?php
function generateUniqueList ($arr){
$ret = array();
foreach ($arr as $value) {
$key = explode("#", $value)[0];
if (array_key_exists($key, $ret)) {
$ret[$key] = $key;
}
else {
$ret[$key] = $value;
}
}
return array_values($ret);
}
$arr = array("yassine#m","yassine#f","Dolmi#m", "yassine#l");
$list = generateUniqueList ($arr);
print_r($list);
I've done a bunch of searching but can't figure this one out.
I have an array like this:
$array = array(cat => 0, dog => 1);
I have a string like this:
I like cats.
I want to see if the string matches any keys in the array. I try the following but obviously it doesn't work.
array_key_exists("I like cats", $array)
Assuming that I can get any random string at a given time, how can I do something like this?
Pseudo code:
array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"
Note that I want to check if "cat" in any form exists. It can be cats, cathy, even random letter like vbncatnm. I am getting the array from a mysql database and I need to know which ID cat or dog is.
You can use a regex on keys. So, if any words of your string equal to the key, $found is true. You can save the $key in the variable if you want. preg_match function allows to test a regular expression.
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (preg_match("/".$key."/", "I like cats")) {
$found = true;
}
}
EDIT :
As said in comment, strpos could be better! So using the same code, you can just replace preg_match:
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (false !== strpos("I like cats", $key)) {
$found = true;
}
}
This should help you achieve what you're trying to do:
$array = array('cat' => 10, 'dog' => 1);
$findThis = 'I like cats';
$filteredArray = array_filter($array, function($key) use($string){
return strpos($string, $key) !== false;
}, ARRAY_FILTER_USE_KEY);
I find that using the array_filter function with a closure/anonymous function to be a much more elegant way than a foreach loop because it maintains one level of indentation.
You could do using a preg_match with the value not in array but in search criteria
if(preg_match('~(cat|dog)~', "I like cats")) {
echo 'ok';
}
or
$criteria = '~(cat|dog)~';
if (preg_match($criteria, "I like cats")) {
echo 'ok';
}
Otherwise you could use a foreach on your array
foreach($array as $key => $value ) {
$pos = strpos("I like cats", $key);
if ($pos > 0) {
echo $key . ' '. $value;
}
}
I have this array
$cart= Array(
[0] => Array([id] => 15[price] => 400)
[1] => Array([id] => 12[price] => 400)
)
What i need is to remove array key based on some value, like this
$value = 15;
Value is 15 is just example i need to check array and remove if that value exist in ID?
array_filter is great for removing things you don't want from arrays.
$cart = array_filter($cart, function($x) { return $x['id'] != 15; });
If you want to use a variable to determine which id to remove rather than including it in the array_filter callback, you can use your variable in the function like this:
$value = 15;
$cart = array_filter($cart, function($x) use ($value) { return $x['id'] != $value; });
There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops...
$value = 15;
foreach ($cart as $i => $v) {
if ($v['id'] == $value) {
unset($cart[$i]);
}
}
If $value is not in the array at all, nothing will happen. If $value is in the array, the entire index will be deleted (unset).
you can use:
foreach($array as $key => $item) {
if ($item['id'] === $value) {
unset($array[$key]);
}
}
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