Php count conditions inside loop [duplicate] - php

This question already has answers here:
PHP - count specific array values
(10 answers)
Closed 9 days ago.
Close my question when it´sdifferent to this not duplicater, the case it´s different in all :
PHP - count specific array values
My question not the same
I have this array for example :
$array_test=array("gren","green","red","red","green","blue");
My idea is know inside loop number of elementos with the condition i want, the array for show it´s more complex and this is only example for understand i need, because try different ways with "count" and don´t show right this number in each case.
I try this :
foreach($array_test as $array_ts) {
if($array_ts=="green") { Count number of elements green /// }
if($array_ts=="red") { Count number of elements red /// }
if($array_ts=="blue") { Count number of elements blue /// }
}
Thank´s for the help, regards.

You can create an array and fill it with the count for each color:
$input = ["gren","green","red","red","green","blue"];
$count = [];
foreach ($input as $color) {
if (array_key_exists($color, $count)) {
$count[$color]++;
} else {
$count[$color] = 1;
}
}
$count will contain:
["green"=>3, "red"=>2, "blue"=>1]

Related

Check if value exists in Array then save as variable [duplicate]

This question already has an answer here:
match exact number in string (and no partial match inside bigger numbers)
(1 answer)
Closed 3 months ago.
Been trying for a while on how to check if a value exists in an array and if so, assign it to a variable to be inserted into the database.
I have the searching working although I can't seem to grab the correct value from the array to which I then need to insert.
Here's where I'm searching for the ID to search by:
{
"questionName": "_questionImgPhoto_176471",
"questionID": "471",
}
Here's the array example:
[0]"/insert/ImgID_466.png"
[1]"/insert/ImgID_471.png"
I am checking if questionID 471 exists somewhere in the array string, if so, insert that row. I am struggling on that part.
So for the insert on questionID 466, the img with 466 in the string will attach to it and so forth.
As you can see 471 does exist in the array example so it should grab that row, here's a snippet of my code below:
for ($i=0; $i < count($content->formValuesT); $i++)
{
if(strpos($content->formValuesT[$i]->questionValue, 'blob') !== false )
{
foreach($content->images_to_upload[$i] as $index => $string) {
if (strpos($string, $content->formValuesT[$i]->questionID) !== FALSE)
{
$file_to_upload = $content->images_to_upload[$i];
}
else
{
echo "wont insert";
}
}
}
}
Has anyone got some pointers or ideas on how to achieve the above? I just can't wrap my head around the practical side of it! in theory I think this is the correct route.
The $file_to_upload is what will be uploaded per row.
Thanks
You can search an array for a specific pattern. Here I made a simple helper function to return the first match or NULL.
$imagesToInsert = ["/insert/ImgID_466.png", "/insert/ImgID_471.png"];
$getImageForId = function(int $id, array $images): ?string {
$matches = preg_grep("/ImgID_{$id}\.png/", $images);
return $matches ? reset($matches) : null;
};
var_dump($getImageForId(471, $imagesToInsert));
var_dump($getImageForId(466, $imagesToInsert));
var_dump($getImageForId(777, $imagesToInsert));
Output
string(21) "/insert/ImgID_471.png"
string(21) "/insert/ImgID_466.png"
NULL

PHP - New numbered var for every object in array [duplicate]

This question already has answers here:
PHP variable variables
(6 answers)
Closed 2 years ago.
I have the following scenario:
Array with multiple waypoints
Want a new variable for every waypoint
Number of waypoints is not fixed
The array stores the address data for the waypoint like street, number, zip, town etc.
I can loop and print the output of the array in foreach loop like:
foreach ($waypoints as $waypoint) {
echo $waypoint->street
echo $waypoint->nb
echo $waypoint->zip
echo $waypoint->town
}
What I'm trying to do is, to get a new variable for each waypoint. E.g:
$wp1 = Data from waypoint 1
$wp2 = Data from waypoint 2
What I have tried:
$waypointCount = count($waypoints);
for ($i = 1; $i < $waypointCount; $i++) {
$wp[$i] = $waypoints->street.' '.$waypoints->nb.' '.$waypoints->zip.' '.$waypoints->town.' '.$waypoints->state;
}
My idea was to count the number of waypoints, set a new variable for each waypoint number and store the corresponding waypointdata in the new variable. I'm kinda stuck on how to create the $wp[i] variables and assign the data to it. Does it need to be a combination with a for and a foreach loop?
Looking for some help to get me on the right direction. Thanks!
It looks like you need to access the correct index of your $waypoints array in your loop. Also, make sure you start your loop with $i = 0 or else you'll skip the first element.
$waypointCount = count($waypoints);
for ($i = 0; $i < $waypointCount; $i++) {
$wp[$i] = $waypoints[$i]->street.' '.$waypoints[$i]->nb.' '.$waypoints[$i]->zip.' '.$waypoints[$i]->town.' '.$waypoints[$i]->state;
}

counting matching elements of multiple arrays [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 4 years ago.
I am looping through two associative array. First one is tags and second is data. I want to count matches for each tags in each data items.
for example
$tags= array("japan", "china", "usa")
$data=array("something...", "something..", "something..")
I want to count how many times japan in each posts ,how many times china in each posts and how many times usa in each post. Unfortunately I am getting count result for only first tag input japan. How to correct this ??
foreach ($tags as $tag) {
foreach ($data as $value) {
$count= substr_count($value,$tag);
}
Put the results in an associative array keyed by tag, and use += to increment the value for that tag.
$results = array();
foreach ($tags as $tag) {
$results[$tag] = 0;
foreach ($data as $value) {
$results[$tag] += substr_count($value, $tag);
}
}

How to count the elements in array which are more than one (php) [duplicate]

This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 7 months ago.
In php,I have one ArrayList. Lets say
$list = {1000,7000,5000,1000,6000,5000,1000,2000};
So what I want to do is that Make count of each element in list:
For example as above ,
1000 comes three times then count of 1000 = 3
5000 comes two times then count of 5000 = 2,etc.
And I want to access that count of different elements separately.
Edit:
Here I have for loop
for($i=0;$i<count($trip);$i++)
{
// Here list will be new everytime for loop run.
$list = $Users->Matches($trip[$i]);
}
// ----------------------------------------------------------------------
Here what I want to do is that "Take all the element of list for value of
$i : 0 to count($trip)" and "add it into another list lets say $allList
and access" as below :
// -----------------------------------------------------------------------
$cnt_arr = array_count_values($allList);
foreach($cnt_arr as $key => $value) {
echo "\n\n Count of ".$key." = ".$value." ";
}
OUTPUT :
Lets say for loop runs first time :
$list = {1000,7000,5000}
Now for loop second time :
$list = {8000,1000,9000}
Now for loop is completed and at the end I want the $allList value as below :
$allList = {1000,7000,5000,8000,1000,9000}(which has all the elements of above-appended list)
So How can I do this ?
Please Guide me. Any help will be appreciated.
Try with array_count_values like
$cnt_arr = array_count_values($list);
foreach($cnt_arr as $key => $value) {
echo "Count of ".$key." = ".$value."<br>";
}
See this LINK
As per your edit,You need to store them like array like
for($i=0;$i<count($trip);$i++)
{
// Here list will be new everytime for loop run.
$temp_list = $Users->Matches($trip[$i]);
foreach($temp_list as $tmp) {
$list[] = $tmp;
}
}

Check if an array contains another array with PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an array contains all elements of another array
I have posted something like this to the Stackoverflow before, but the answers do not fully satisfy me. That's why I'm posting the question again, but changing the question all along.
Some people helped me to construct a function that checks if an array($GroupOfEight[$i]) that is an element of a multidimensional array($GroupOfEight) equals another array($stackArray), disregarding the number ordering in the arrays.
However, what I need to check is whether the mentioned array($stackArray) contains any another array($GroupOfEight[$i]) in the multidimensional array($GroupOfEight) or not, that means main array($stackArray) can consist more elements than subarrays($GroupOfEight[$i]).
Here is the one working code that I've gathered so far, but need to be modified to the version I want:
<?php
$GroupOfEight = array (
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10)
);
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
/*$stackArray gets value with POST Method by URL parameter.
This is just the example. As you see this array contains
$GroupOfEight[4], and also it contains many other numbers.*/
/* The function given below checks if $stackArray equals any
of the subarrays of $GroupOfEight. However, we want to check
if $stackArray caontains any of the subarrays of function.
If it does, function should return the index number, if it
doesnt it should return -1.*/
function searcheight($stackArray,$GroupOfEight){
for($i=0; $i<count($GroupOfEight);$i++){
$containsSearch = (count(array_intersect($stackArray,$GroupOfEight[$i])) == count($stackArray) && count(array_intersect($stackArray,$GroupOfEight[$i])) == count($GroupOfEight[$i]));
if($containsSearch){
return $i; //This specifies which index in GroupOfEight contains a matching array
}
}
return -1;
}
// Calling the function that is given above.
echo searcheight($stackArray,$GroupOfEight);
?>
Any logical ideas or solutions will kindly be much appreciated. Thanks.
This one is fast:
function contains_array($array){
foreach($array as $value){
if(is_array($value)) {
return true;
}
}
return false;
}
You can try
$GroupOfEight = array(
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10));
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
function searcheight($stackArray, $GroupOfEight) {
$list = array();
for($i = 0; $i < count($GroupOfEight); $i ++) {
$intercept = array_intersect($GroupOfEight[$i], $stackArray);
$len = count($intercept);
if ($len % 4 == 0) {
$list[$i] = $len;
}
}
arsort($list);
if (empty($list))
return - 1;
return key($list);
}
echo searcheight($stackArray, $GroupOfEight);
Output
5

Categories