Link to home
Start Free TrialLog in
Avatar of VAL1N
VAL1N

asked on

PHP Inserting new data into arrays if it doesn't exist.

I have about 10 categories that change all the time the page is refreshed and therefore, every time the script is loading, I need to insert the category name into array if it does not exist with an integer 1, but if the category already exists in the array, I need to get the integer that represents how many items were counted in that category and increase it by one.

For example:

foreach loop:

category name = "CAT1" and it doesn't exist, so we add it to the array "CAT1" => "1" means it is the first time we see any item from this category.
now we do the same over and over again and if we see the item with category name CAT1, we should know that we already had one item from that category in the past, so we increase the amount in the array and now we have "CAT1" => "2".

Thank you for help.
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

$source = array("CAT1","CAT2","CAT3");

$categories = array();
foreach($source as $sourceCat)
{
  @$categories[$sourceCat]++;
}

print_r($categories);
Avatar of VAL1N
VAL1N

ASKER

I don't know the list of categories, so I need to add the categories into the array as I go through the foreach loop.

$categories = array();

foreach ($matches[1] as $num => $value) {

$tmp_category = $matches[5][$num];

//check if category exists or not, if not then add with integer 1, if does, then i++

}

so if $tmp_category does not exist in $categories, then we add it in and it should have 1 as integer in it so that I know later on, how many times that category had items in it.

but if $tmp_category already exists in $categories (because we added it earlier on in the foreach loop), then we just increase it's value by 1
ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial