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]);
}
}
Related
I have this array:
$test = [
['teams' => ['home' => 'Lazio']],
['teams' => ['away' => 'Inter']]
];
I need to search Inter, so I did:
$key = array_search('Inter', array_column($test, 'teams'));
var_dump($test[$key]);
but it returns false as $key.
array_search() doesn't search nested arrays. There's no built-in functionthat does this, so just use a loop.
$key == null;
foreach (array_column($test, 'teams') as $i => $teams) {
if (in_array('Inter', $teams)) {
$key = $i;
break;
}
}
if ($key !== null) {
var_dump($test[$key]);
}
$needle = array_flip(['Inter']);
$result = array_filter(array_column($test, 'teams'), function(array $item) use ($needle) {
return array_intersect_key(array_flip($item), $needle);
});
using $needle as an array (and as result array_intersect_key) just in case you need to find more than one value.
You can change array_intersect_key to isset and single $needle value (instead of array).
also, is better to avoid using the array_search, (also in_array) functions for big arrays because of their complexity of algorithm (eq low performance)
I'm bored. You can filter out non-matching items and then get the key.
You can search for it anywhere in the array without specifying home, away or other:
$key = key(array_filter($test, function($v) { return in_array('Inter', $v['teams']); }));
Not the preferred way, but if there is only home and away you can search using an array:
($key = array_search(['away' => 'Inter'], array_column($test, 'teams'))) ||
($key = array_search(['home' => 'Inter'], array_column($test, 'teams')));
Or with one array_column call:
($t = array_column($test, 'teams')) && ($key = array_search(['away' => 'Inter'], $t)) ||
($key = array_search(['home' => 'Inter'], $t));
All of the code above returns the key of the first match.
I am trying to compare a values in array and select the next value in the array based on a selected value.
For example
array(05:11,05:21,05:24,05:31,05:34,05:41,05:44,05:50,05:54);
and if the the search value is for example 05:34, the one that is returned to be 05:41. If the value is 05:50, 05:54 is returned
I did find something that might help me on this post, but because of the : in my values it will not work.
Any ideas how can I get this to work?
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
UPDATE
Maybe I should somehow convert the values in the array in something more convenient to search within - Just a thinking.
Using the internal pointer array iterator -which should be better from the performance point of view than array_search- you can get the next value like this:
$arr = array('05:11','05:21','05:24','05:31','05:34','05:41','05:44','05:50','05:54');
function getClosest($search, $arr) {
$item = null;
while ($key = key($arr) !== null) {
$current = current($arr);
$item = next($arr);
if (
strtotime($current) < strtotime($search) &&
strtotime($item) >= strtotime($search)
) {
break;
} else if (
strtotime($current) > strtotime($search)
) {
$item = $current;
break;
}
}
return $item;
}
print_r([
getClosest('05:50', $arr),
getClosest('05:34', $arr),
getClosest('05:52', $arr),
getClosest('05:15', $arr),
getClosest('05:10', $arr),
]);
This will output :-
Array (
[0] => 05:50
[1] => 05:34
[2] => 05:54
[3] => 05:21
[4] => 05:11
)
Live example https://3v4l.org/tqHOC
Using array_search() you can find index of array item based of it value. So use it to getting index of searched item.
function getClosest($search, $arr) {
return $arr[array_search($search, $arr)+1];
}
Update:
If search value not exist in array or search value is last item of array function return empty.
function getClosest($search, $arr) {
$result = array_search($search, $arr);
return $result && $result<sizeof($arr)-1 ? $arr[$result+1] : "";
}
Check result in demo
First convert your array value in string because of you use the ':' in the value like
array('05:11','05:21','05:24','05:31','05:34','05:41','05:44','05:50','05:54');
Then use below code to find the next value from the array
function getClosest($search, $arr) {
return $arr[array_search($search,$arr) + 1];
}
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';
});
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)
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]);
}