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.
VAL1NAsked:
Who is Participating?
 
gr8gonzoConnect With a Mentor ConsultantCommented:
$categories = array();
foreach ($matches[1] as $num => $value) {
$tmp_category = $matches[5][$num];
@$categories[$tmp_category]++;
}
0
 
gr8gonzoConsultantCommented:
$source = array("CAT1","CAT2","CAT3");

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

print_r($categories);
0
 
VAL1NAuthor Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.