Count number of values in array with variables - php

I'm trying to count the number of times a certain value turns up in an array. Except this value will always increment by 1, and there is an unknown number of these values in the array.
Example:
$first = array( 'my-value-1','my-value-2','my-value-3' );
$second = array( 'my-value-1','my-value-2','my-value-3', 'my-value-4', 'my-value-5' );
My goal is to be able to retrieve a count of 3 for $first and a count of 5 for $second in the example above.
There may be other values in the array, but the only values I'm interested in counting are the ones that start with my-value-.
I won't know the number of the values in the array, but they will always start with my-value- with a number added to the end.
Is there a way to count the number of times my-value- shows up in the array with some sort of wildcard?

Use a regex to filter the array and count the values that match. You could also use ^ to force it to be at the beginning ^my-value-\d+:
$count = count(preg_grep('/my-value-\d+/', $first));
You could also do it this way. Again you could use === 0 instead to make it match at the beginning:
$count = count(array_filter($first, function($v) {
return strpos($v, 'my-value-') !== false;
}));

A quick function to count values by providing a partial string and the target array.
Note: search is case-insensitive.
function countValues($prefix, $array) {
return count(array_filter($array, function($item) use ($prefix) {
return stripos($item, $prefix) !== false;
}));
}
Usage:
$count = countValues('my-value', $first);

According to your question, "they will always start with my-value- with a number added to the end." So you don't need a regex, just a count of the number of items in your array, using PHP's built-in count() function. Try:
<?php
$first = array( 'my-value-1','my-value-2','my-value-3' );
$second = array( 'my-value-1','my-value-2','my-value-3', 'my-value-4', 'my-value-5' );
$size_of_first = count($first);
$size_of_first = count($first);
echo $size_of_first; //Will echo 3
echo $size_of_first; //Will echo 5
?>

Related

How to search $_POST for dynamic added input values?

I have a form where i add inputs on the fly.
The names of the inputs start the same but has a number added on the end:
<input type="number" name="number_of_floors_house_'+i+'">
Now, when i post my form i would like to loop threw this inputs.
So i need something like array_search($_POST['number_of_floors_house_%']
Or find all $POST['keys'] that starts with 'number_of_floors_house' and loop them threw to get it's values :)
Can you help please?
EDIT
I've tried:
$houses_and_floors = array_search('number_of_floors_house_%', $_POST);
var_dump($houses_and_floors);
Change your input to something like this:
<input type="number" name="number_of_floors['+i+']">
The square brackets make the input submit as an array, so you could then loop through all the values easier:
foreach($_POST['number_of_floors'] as $house_number => $value) {
// $house_number will be whatever number was added to the form element.
// $value is the actual input boxes value
}
You could use an array_filter() to pick out the pieces of $_POST you actually want like this
//fake up a post array
$_POST = ['aa'=>1, 'bb'=>2, 'number_of_floors_house_1'=>2, 'number_of_floors_house_2'=>2,'number_of_floors_house_3'=>4];
function picker($v, $k)
{
return strpos($k, 'number_of_floors_house') !== FALSE;
}
$res = array_filter($_POST, 'picker', ARRAY_FILTER_USE_BOTH);
print_r($res);
RESULT
Array
(
[number_of_floors_house_1] => 2
[number_of_floors_house_2] => 2
[number_of_floors_house_3] => 4
)
You can filter for array keys matching a given prefix with array_filter() and strncmp():
$prefix = 'number_of_floors_';
$length = strlen($prefix);
$nof = array_filter($_POST, function($key) use ($prefix, $length) {
return strncmp($prefix, $key, $length) === 0;
}, ARRAY_FILTER_USE_KEY);
This will filter your post data for all array members with the defined prefix. Note that we're checking the prefix length outside the function to avoid a redundant repeated evaluation inside the function (which is executed for once each array member). You could, of course, also just hard-code this for a single use-case and skip the leading variables above:
$nof = array_filter($_POST, function($key) {
return strncmp('number_of_floors_', $key, 17) === 0;
}, ARRAY_FILTER_USE_KEY);
...which would compare the first 17 characters of each key with the defined string. Again, you could also do this with substr() in place of strncmp(), with return substr($key, 0, $length) === $prefix as the filter condition. I chose the former for this example, since it's a function explicitly for the "binary safe string comparison of the first n characters".

How can I output 2 random values from an array?

I'm trying to make a simple PHP script for school. I need to output 2 random students from the array $leerlingen (Leerlingen = students).
It work's fine when I use echo $leerlingen within the foreach loop, but when I use the return statement it stops executing, because when return is used, it ends the function.
Code:
$leerlingen = array("tobias", "hasna", "aukje", "fred", "sep", "koen", "wahed", "anna", "jackie", "rashida", "winston", "sammy", "manon", "ben", "karim", "bart", "lisa", "lieke");
shuffle($leerlingen);
function maakGroepjes($leerlingen) {
$begin = 1;
foreach ($leerlingen as $leerling) {
if ($begin <= 2) {
echo $leerling;
$begin++;
}
}
}
echo maakGroepjes($leerlingen);
Can anyone tell me how to solve this problem?
You can return only one value inside a function, in this case is an array. I assume that the array have at least two values.
<?php
$leerlingen = array(
"tobias", "hasna", "aukje", "fred", "sep", "koen", "wahed", "anna", "jackie", "rashida", "winston", "sammy", "manon", "ben", "karim", "bart", "lisa", "lieke"
);
shuffle($leerlingen);
function maakGroepjes($leerlingen) {
//your result array
$result = array();
//Picking 2 random entries out of an array to $keys
$keys = array_rand($leerlingen, 2);
//Returning the array with two values
return array($leerlingen[$keys[0]], $leerlingen[$keys[1]]);
}
//assign the values to the vars
list($one, $two) = maakGroepjes($leerlingen);
//printing
echo $one . "<br>\n";
echo $two . "<br>\n";
?>
array_rand and other functions (rand) that rely on libc have a bad standard distribution. I'd always recommend using mt_rand() if you need it to be equally distributed, otherwise some entries will be heavily favored.
This is a good easy replacement for numerical arrays:
function array_mt_rand($array) {
return $array[ mt_rand( 0, count($array)-1 ) ];
}
$one = array_mt_rand($array);
$two = array_mt_rand($array);
You may need some extra checks if you have a small array and always want two distinct values though.
You could always try something like this.
function maakGroepjes($leerlingen) {
do {
$first_student = array_rand($leerlingen);
$second_student = array_rand($leerlingen);
} while ($leerlingen[$first_student] == $leerlingen[$second_student]);
return [$leerlingen[$first_studen], $leerlingen[$second_student]];
}
Which returns this.
Array
(
[0] => manon
[1] => winston
)
Also, the difference between a function printing/echo'ing information and returning information is pretty big.
You can't assign a variable to the echo statement inside of a function, whereas you could assign a variable to the return statement.
I would approach this a little differently.
function maakGroepjes($leerlingen) {
shuffle($leerlingen); // randomize the list of students
return array_chunk($leerlingen, 2); // break in into groups of two and return it
}
Then with
$groepjes = maakGroepjes($leerlingen);
you can generate all of the groups at once. No worries about repetition. This way if you need multiple groups, you can loop over the list of groups. If you really only need one group of two, then that will be
$groepjes[0];
which you can ouptut however you like. A very simple example:
foreach ($groepjes[0] as $student) echo "$student<br>";
Try this:
if ($begin <= 2) {
echo $leerling;
$begin++;
} else {
return
}
What this does is: every time through the loop, it looks at $begin. If it's less than or equal to two, it echoes that student and increments $begin. Otherwise, if it's greater than two, it returns, ending the function (and thus, the loop).
A perhaps better way to do it would be to just look at the ordinal directly:
foreach ($leerlingen as $ord => $leerling) {
echo $leerling;
if ($ord == 1) return;
}
Note the syntax in the loop definition. The "old =>" part sets the ordinal value as a variable as you loop through, letting you see which entry in the array you are currently on. So, this just loops through printing students. When it has printed the second student (remember, arrays are counted 0, 1, 2...) it returns.
Also, you probably don't want to echo maakGroepjes(). That function is what is echoing the student names. You probably don't want to echo the function result unless the function compiles the names into a string and returns the string or something.

Compare All strings in a array to all strings in another array, PHP

What i am trying to do is really but i am going into a lot of detail to make sure it is easily understandable.
I have a array that has a few strings in it. I then have another that has few other short strings in it usually one or two words.
I need it so that if my app finds one of the string words in the second array, in one of the first arrays string it will proceed to the next action.
So for example if one of the strings in the first array is "This is PHP Code" and then one of the strings in the second is "PHP" Then it finds a match it proceeds to the next action. I can do this using this code:
for ( $i = 0; $i < count($Array); $i++) {
$Arrays = strpos($Array[$i],$SecondArray[$i]);
if ($Arrays === false) {
echo 'Not Found Array String';
}
else {
echo 'Found Array String';
However this only compares the First Array object at the current index in the loop with the Second Array objects current index in the loop.
I need it to compare all the values in the array, so that it searches every value in the first array for the First Value in the second array, then every value in the First array for the Second value in the second array and so on.
I think i have to do two loops? I tried this but had problems with the array only returning the first value.
If anyone could help it would be appreciated!
Ill mark the correct answer and + 1 any helpful comments!
Thanks!
Maybe the following is a solution:
// loop through array1
foreach($array1 as $line) {
// check if the word is found
$word_found = false;
// explode on every word
$words = explode(" ", $line);
// loop through every word
foreach($words as $word) {
if(in_array($word, $array2)) {
$word_found = true;
break;
}
}
// if the word is found do something
if($word_found) {
echo "There is a match found.";
} else {
echo "No match found."
}
}
Should give you the result you want. I'm absolute sure there is a more efficient way to do this.. but thats for you 2 find out i quess.. good luck
You can first normalize your data and then use PHP's build in array functions to get the intersection between two arrays.
First of all convert each array with those multiple string with multiple words in there into an array only containing all words.
A helpful function to get all words from a string can be str_word_count.
Then compare those two "all words" arrays with each other using array_intersect.
Something like this:
$words1 = array_unique(str_word_count(implode(' ', $Array), 1));
$words2 = array_unique(str_word_count(implode(' ', $SecondArray), 1));
$intersection = array_intersect($words1, $words2);
if(count($intersection))
{
# there is a match!
}
function findUnit($packaging_units, $packaging)
{
foreach ($packaging_units as $packaging_unit) {
if (str_contains(strtoupper($packaging[3]), $packaging_unit)) {
return $packaging_unit;
}
}
}
Here First parameter is array and second one is variable to find

Get count of substring occurrence in an array

I would like to get a count of how many times a substring occurs in an array. This is for a Drupal site so I need to use PHP code
$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb',
'usa-ny-wch', 'usa-ny-li');
I need to be able to call a function like foo($ar_holding, 'usa-ny-'); and have it return 3 from the $ar_holding array. I know about the in_array() function but that returns the index of the first occurrence of a string. I need the function to search for substrings and return a count.
You could use preg_grep():
$count = count( preg_grep( "/^usa-ny-/", $ar_holding ) );
This will count the number of values that begin with "usa-ny-". If you want to include values that contain the string at any position, remove the caret (^).
If you want a function that can be used to search for arbitrary strings, you should also use preg_quote():
function foo ( $array, $string ) {
$string = preg_quote( $string, "/" );
return count( preg_grep( "/^$string/", $array ) );
}
If you need to search from the beginning of the string, the following works:
$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb',
'usa-ny-wch', 'usa-ny-li');
$str = '|'.implode('|', $ar_holding);
echo substr_count($str, '|usa-ny-');
It makes use of the implode function to concat all array values with the | character in between (and before the first element), so you can search for this prefix with your search term. substr_count does the dirty work then.
The | acts as a control character, so it can not be part of the values in the array (which is not the case), just saying in case your data changes.
$count = subtr_count(implode("\x00",$ar_holding),"usa-ny-");
The \x00 is to be almost-certain that you won't end up causing overlaps that match by joining the array together (the only time it can happen is if you're searching for null bytes)
I don't see any reason to overcomplicate this task.
Iterate the array and add 1 to the count everytime a value starts with the search string.
Code: (Demo: https://3v4l.org/5Lq3Y )
function foo($ar_holding, $starts_with) {
$count = 0;
foreach ($ar_holding as $v) {
if (strpos($v, $starts_with)===0) {
++$count;
}
}
return $count;
}
$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb',
'usa-ny-wch', 'usa-ny-li');
echo foo($ar_holding, "usa-ny-"); // 3
Or if you don't wish to declare any temporary variables:
function foo($ar_holding, $starts_with) {
return sizeof(
array_filter($ar_holding, function($v)use($starts_with){
return strpos($v, $starts_with)===0;
})
);
}

PHP: How do I check the contents of an array for my string?

I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;

Categories