I have a array inside my PHP app that looks like this:
Array
(
[0] => Array
(
[name] => Name1
[language] => 1
)
[1] => Array
(
[name] => Name2
[language] => 1
)
)
How can I check that "language" with value 1 doesnt appear twice, as effectively as possible?
$dupe = 0;
foreach($yourarray as $key => $val) {
if(array_key_exists($seen, $val['language'])) {
// a duplicate exists!
$dupe = 1;
// could do other stuff here too if you want,
// like if you want to know the $key with the dupe
// if all you care about is whether or not any dupes
// exist, you could use a "break;" here to early-exit
// for efficiency. To find all dupes, don't use break.
}
$seen[$val['language']] = 1;
}
// If $dupe still = 0 here, then no duplicates exist.
Tried the PHP function array_unique?
(Read the comments/user contributed notes below, especially the one by regeda at inbox dot ru, who made a recursive function for multi-dimensional arrays)
Related
How can I loop through set of session array and check if $_session['items'][1][p_alt-variation-1] and so on, are exist? the [p_alt-variation-{n}] elements are dynamic if certain item has these add-on variations, so it could be as much as more than 1
print_r($_session['items'])
Array
(
[0] => Array
(
[p_name] => Hovid PetSep
[p_code] => 336910
[p_coverImg] => 14-1460428610-ulNvG.jpg
[p_id] => 14
[p_price] => 24.50
[p_qty] => 2
)
[1] => Array
(
[p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted)
[p_code] => 2102649
[p_coverImg] => 12-1460446199-wI5qx.png
[p_id] => 12
[p_price] => 68.00
[p_alt-variation-1] => Red
[p_alt-variation-2] => L
[p_qty] => 1
)
)
I want to show for user if certain item has various variations in their cart if exist, how to look for element in array if contains string like [p_alt-variation-{n}] through?
I use foreach($_SESSION['items'] as $cart_item){ ... } to loop all cart items to show item's info.
Thanks for advice.
Not a regex guru, but you could just get the keys and check using preg_grep. If it has more than one key for that keyword, just count the results.
Here's the idea:
foreach($_SESSION['items'] as $cart_item) { // loop the items
$keys = array_keys($cart_item); // get the keys of the current batch
// make the expression
$matches = preg_grep('~^p_alt\-variation\-\d+~i', $keys); // simply just checking the key name with has a number in the end, adjust to your liking
if(count($matches) > 1) { // if it has more than one, or just change this to how many do you want
echo 'has more than one variation';
}
}
If you wanted to use some of that keys, just use the results that was found inside $matches:
if(count($matches) > 1) {
foreach($matches as $matched_key) {
echo $cart_item[$matched_key];
}
}
The session variables are just like any other array values; you can always use isset function. Please refer: http://php.net/manual/en/function.isset.php
Ran into a little snag and wondering if there is a "best practices" way around it.
So I just learned that "A php foreach will execute on the entire array regardless. Test unsetting a value that is next in iteration. It will iterate on the offset, but the value will be null. – Kevin Peno Dec 22 '09 at 21:31" from How do you remove an array element in a foreach loop?
It's the first part of that that is messing with me. I'm iterating through an array with foreach. It's a search function so I'm removing the element I just searched for, so when the loop runs again its minus that element.
I do NOT want to reindex if at all possible, although if I have to I can.
Array
(
[0] => Array
(
[0] => a
[1] => aa
[2] => aaa
)
[1] => Array
(
[0] => b
[1] => bb
[2] => bbb
)
[2] => Array
(
[0] => c
[1] => cc
[2] => ccc
)
[3] => Array
(
[0] => d
[1] => dd
[2] => ddd
)
)
foreach($array as $key=>$value) {
$searchresult[] = search function returns various other keys from array
foreach($searchresult as $deletionid) {
unset($array[$deletionid]);
}
}
So on the first iteration it uses $array[0] obviously but the $searchresults might return 4,5,6,7. So those keys are removed from $array.
Yet the foreach loop still iterates through those and gives me back a bunch of empty arrays.
I did read How does PHP 'foreach' actually work? and I get some of it.
Thanks
In my opinion, the best way to remove array elements based on indexes is to use the array_* set of functions, like array_diff and array_intersect (or array_diff_key and array_intersect_key in your situation).
$indexes_to_remove = array(2,3,4);
$indexes_to_remove = array_flip($indexes_to_remove);
$array = array_diff_key($array,$indexes_to_remove);
If the array is guaranteed to be exhausted at some point, you can use this:
while (true) {
$searchresult[] = search function returns various other keys from array
foreach($searchresult as $deletionid) {
unset($array[$deletionid]);
}
if (count($array) === 0) {
break;
}
}
And yes I know while (true) is pretty evil, but I find in cases like these it does exactly what is needed.
If you want to prevent it from infinite looping you could always add a variable, increment each iteration, and break when it reaches a high value that should never happen (like 10 * count($array))
supposing I have an array like the one below:
Array
(
[0] => Array
(
[id] => 1
[title] => Group1
[description] => This is the group1.
)
[1] => Array
(
[id] => 2
[title] => Group2
[description] => This is group2.
)
)
Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?
Thanks for any help.
Try this :
$title = "Group2";
foreach($your_array as $val){
if($val['title'] == $title){
echo $val['description'];
break; //cut back on unnecessary looping
}
}
Try like this
foreach($myarray as $val){
if($val['title'] == "Group2"){
echo 'This is description '.$val['description'];
}
}
You'll have to iterate over the main array and scan it for that title.
Assuming your main array is called $groups :
$title = 'Group2';
foreach($groups as $key => $group){
if ($group['title'] == $title){
$groupDescription = $group['description'];
// if you need to reference this group again, save it's key.
$groupKey = $key;
}
}
You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.
Given
[0] => Array
(
[0] => ask.com
[1] => 2320476
)
[1] => Array
(
[0] => amazon.com
[1] => 1834593
)
[2] => Array
(
[0] => ask.com
[1] => 1127456
)
I need to remove duplicate values solely based on first value, regardless of what any other subsequent values may be. Notice [0][1] differs from [2][1] yet I consider this as a duplicate because there are two matching first values. The other data is irrelevant and shouldn't be considered in comparison.
Try this, assuming that $mainArray is the array you have.
$outputArray = array(); // The results will be loaded into this array.
$keysArray = array(); // The list of keys will be added here.
foreach ($mainArray as $innerArray) { // Iterate through your array.
if (!in_array($innerArray[0], $keysArray)) { // Check to see if this is a key that's already been used before.
$keysArray[] = $innerArray[0]; // If the key hasn't been used before, add it into the list of keys.
$outputArray[] = $innerArray; // Add the inner array into the output.
}
}
print_r($outputArray);
I want to check only the value [id] for duplicates, and remove all keys where this "field" [id] is a duplicate.
Example: If I have numbers 1,2,1. I want the result to be 2, not 1,2. And criteria for duplicates is determined only by checking [id], not any other "field".
Original array:
Array
(
[0] => Array
(
[name] => John
[id] => 123
[color] => red
)
[1] => Array
(
[name] => Paul
[id] => 958
[color] => red
)
[2] => Array
(
[name] => Jennifer
[id] => 123
[color] => yellow
)
)
The result I want:
Array
(
[0] => Array
(
[name] => Paul
[id] => 958
[color] => red
)
)
I agree with everyone above, you should give us more information about what you've tried, but I like to code golf, so here's a completely unreadble solution:
$new_array = array_filter($array, function($item) use (&$array){
return count(array_filter($array, function($node) use (&$item){
return $node['id'] == $item['id'];
})) < 2;
});
This should be fairly easy to accomplish with a couple of simple loops:
set_time_limit(0); // Disable time limit to allow enough time to process a large dataset
// $items contains your data
$id_counts = array();
foreach ($items as $item) {
if (array_key_exists($item['id'], $id_counts)) {
$id_counts[$item['id']]++;
} else {
$id_counts[$item['id']] = 1;
}
}
for ($i = count($items); $i >= 0; $i--) {
if ($id_counts[$items[$i]['id']] > 1) {
array_splice($items, $i, 1);
}
}
Result:
Array
(
[0] => Array
(
[name] => Paul
[id] => 958
[color] => red
)
)
While there are neater ways to do it, one advantage of this method is you're only creating new arrays for the list of ids and duplicate ids and the array_splice is removing the duplicates from the original array, so memory usage is kept to a minimum.
Edit: Fixed a bug that meant it sometimes left one behind
This is a very basic approach to the answer and I am sure there are much better answers however I would probably start by doing it the way I would on paper.
I look at the first index, check its value. Then I go through every other index making note of their index if the value is the same as my originally noted value. Once I have gone through the list if I have more than one index with that particular value I remove them all (starting with the highest index, so as to not affect indexes of the others while deleting).
Do this for all other indexes till you reach the end of the list.
It is long winded but will make sure it removes all values which have duplicates. and leaves only those which originally had no duplicates.
function PickUniques(array $items){
// Quick way out
if(empty($items)) return array();
$counters = array();
// Count occurences
foreach($items as $item){
$item['id'] = intval($item['id']);
if(!isset($counters[$item['id']])){
$counters[$item['id']] = 0;
}
$counters[$item['id']]++;
}
// Pop multiples occurence ones
foreach($counters as $id => $occurences){
if($occurences > 1){
unset($counters[$id]);
}
}
// Keep only those that occur once (in $counters)
$valids = array();
foreach($items as $item){
if(!isset($items[$item['id']])) continue;
$valids[$item['id']] = $item;
}
return $valids;
}
Try this one :)