I've got an array containing
"1", "2", "3", "4"
And I use array_rand to select one of those numbers randomly five times. Then I want to count how many of the result of array_rand that have been chosen multiple times like the number 2 got chosen 2 times and number 3 got chosen 2 times.
I have tested doing this
$array = array($kort1[$rand_kort1[0]], $kort1[$rand_kort2[0]], $kort1[$rand_kort3[0]], $kort1[$rand_kort4[0]], $kort1[$rand_kort5[0]]);
$bank = array_count_values($array);
if (in_array("2", $bank)) {
echo "You got one pair";
} elseif(in_array("2", $bank) && (???)) {
echo "You got two pair";
}
it will tell me "You got one pair" if one of those numbers were randomly chosen 2 times but my problem is I don't know how to make it say "You got two pairs" if 2 of those numbers were chosen 2 times.
the result of $bank could be
[4] => 1 [3] => 2 [1] => 2
Try this: (This will work even if your array has more than 4 values)
$count = 0;
foreach ($bank as $key=>$value) {
if ($value === 2) {
$count++;
}
}
if ($count) {
$s = $count > 1 ? 's' : '';
echo "You got $count pair$s";
}
It will show an output like You got 1 pair. If you want to use words (like you mentioned in your question), you can use NumberFormatter class
You can use array_filter to appy a function to each element of your array
$bank=array(4 => 1, 3 => 2, 1 => 2); // Your array
function pairs($var) {
return($var === 2); // returns value if the input integer equals 2
}
$pairs=count(array_filter($bank, "pairs")); // Apply the function to all elements of the array and get the number of times 2 was found
if ($pairs === 1)
{
echo "you got one pair";
}
if ($pairs === 2) {
echo "you got two pairs";
}
EDIT
Thought of this one liner later:
$pairs=count(array_diff($bank, array(1,3,4)));
Related
To calculate the sum of values based on the input and match it with names in an array
$input = '500';
$array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);
need answer like this output
jhon,puppy and bolda,rehana
This code creates an array $data that contains names and their respective values. It then uses a foreach loop to iterate through the array and subtract the value of each name from the input until the input becomes zero. The names of all the values that were subtracted from the input are stored in an array $names. Finally, if the array $names is not empty, the names are echoed using implode separated by "and". If the array is empty, it means no match was found and a message "No match found" is echoed.
So I'm going to go out on a guess here. (this sounds like cheating on homework lmao).
You need to output pairs of names where the two names add upto 500 (the input).
This probably wont be the most optimal solution, but it should be a solution that works?
$input = 500;
// using shorthand array formatting
$array1 = [
200 => 'jhon',
300 => 'puppy',
50 => 'liza',
150 => 'rehana',
400 => 'samra',
100 => 'bolda'
];
// create an array that holds names we have already processed.
$namesProcessed = [];
// loop over the names trying to find a compatible partner
foreach ($array1 as $points => $name) {
foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {
// Don't partner with yourself...
if ($name == $namePotentialPartner) {
continue;
}
// Don't partner with someone that has already been processed.
if (in_array($namePotentialPartner, $namesProcessed)) {
continue;
}
// test if the two partners add up to the input
if ($input == ($points + $pointsPotentialPartner)) {
// if this is the first partner set, don't put in 'and'
if (count($namesProcessed) == 0) {
echo $name . ', ' . $namePotentialPartner;
} else {
echo ' and ' . $name . ', ' . $namePotentialPartner;
}
$namesProcessed[] = $name;
$namesProcessed[] = $namePotentialPartner;
}
}
}
Hope this helps.
I'm trying to solve a problem where you write a script and then get:
multiple test cases with 5 integer user inputs
one test case with one single 0
I want to check the number of user inputs and then determine which code is executed.
Something like this:
if(fscanf(STDIN, '%d%d%d%d%d', $a, $b, $c, $d, $e) == 5) {
echo "Five inputs";
} elseif(fscanf(STDIN, '%d', $a) == 1) {
echo "Only one input";
}
So if you get for example the input 1 2 3 4 5 it should echo "Five inputs" but if you only get 0 it should echo "Only one input".
There are a couple of problems with your code. The first is that you scan using %d%d%d%d%d, this is looking for a continuous number, you would at least have to have spaces in there to delimit the values. The second is that if this fails, it will ask for input again for the single input check.
This code reads a line from the input and then splits it (using explode()) into parts. Te middle bit just checks for numerical values and you can adjust this if needed. Then the last part just checks how many parts there are (using count($inputs)) and outputs the appropriate message.
$input = fgets(STDIN);
$inputs = explode(" ", $input);
// Check numeric
foreach ( $inputs as $index => $check ) {
if ( !is_numeric($check) ) {
echo "Input $index is not numeric".PHP_EOL;
}
}
if(count($inputs) == 5) {
echo "Five inputs";
} elseif(count($inputs) == 1) {
echo "Only one input";
}
What I'm trying to do is make a list of entries from a form, but I do not want the same entry to be displayed multiple times in the list if it was entered more than once in the form. For example, say one person enters "1" but then two people enter "2", I would only want the 2 to appear once in the list. What function would I be able to use for this?
The best way should be to store all your entries in an array (basic numerical indexed array) and then, remove duplicate with
uniqueEntries = array_unique($yourEntries);
The documentation : array_unique
example of code:
$entries = array();
$entries[] = 1;
$entries[] = 1;
$entries[] = 2;
$entries = array_unique($entries);
print_r($entries);
will output:
Array
(
[0] => 1
[2] => 2
)
In this case you should use PHP Arrays. Arrays are 2-dimensional tables.
/* Array
* key => value
* #key personID
* #value optionValue
*/
$array = array(
1 => 1, // Person 1 chose Option 1
2 => 2, // Person 2 chose Option 2
3 => 2 // Person 3 chose Option 2
);
print_r($array);
Prints
Array
(
[1] => 1
[2] => 2
[3] => 2
)
You are now able to fetch a set of unique values by accessing the array via array_unique($array);.
$array_unique = array_unique($array);
$array_unique_values = array_values($array_unique);
// Access array values directly and store into variables.
// Notice that arrays in PHP start with the index zero.
$option1 = $array_unique_values[0];
$option2 = $array_unique_values[1];
echo "Option #1: " . $option1 . "\n";
echo "Option #2: " . $option2;
Prints
Option #1: 1
Option #2: 2
VoilĂ .
You have no built-in function for that in PHP. But you could try with something like:
$echoList = array();
function echoOnce( $text )
{
global $echoList;
if(!in_array($text, $echoList)) {
echo $text;
$echoList[] = $text;
}
}
And then just use echoOnce( "whatever" ) instead of echo "whatever"
I'm having troubles finding the code for this:
I have this array:
$filtros['code'] = 1
$filtros['name'] = 'John'
$filtros['formacion_c_1'] = 2
$filtros['formacion_c_2'] = 1
$filtros['formacion_c_3'] = 2
And I need to catch the number of each "formacion_c_{number}" and his value
echo "The Formation number {number} has the value $filtros[formacion_c_{number}]";
the result that I need is something like :
The Formation number 1 has the value 2.
The Formation number 2 has the value 1.
The Formation number 3 has the value 2.
surely the solution is with some preg_split or preg_match, but I can't handle this
foreach($filtros as $key=>$val){
if(preg_match('/^formacion_c_(\d)+$/', $key, $match) === 1){
echo "The Formation number {$match[1]} has the value $val";
}
}
Demo: http://ideone.com/iscQ7
Why don't you use multidimensional arrays for this?
Instead of:
filtros['formacion_c_1'] = 2
filtros['formacion_c_2'] = 1
filtros['formacion_c_3'] = 2
Why not:
filtros['formacion_c']['1'] = 2
filtros['formacion_c']['2'] = 1
filtros['formacion_c']['3'] = 2
[edit]
I noticed in the comments you said you get this array from a form. You can have multidimensional arrays in HTML forms.
[/edit]
If you can't change the code I guess you could loop through each element and compare the key:
$keyStart = 'formacion_c_';
foreach($filtros as $key => $value) {
if(strstr($key, $keyStart)) {
$id = str_replace($keyStart, '', $key);
}
}
I have the following multidimensional array:
<? $array = array(0 => 2, 3 => 1, 5 => 1 );
Which looks like this when printed:
Array ( [0] => 2 [3] => 1 [5] => 1 ); //the value in brackets is the shoe size
The first part of array is a "shoe size", and the second part of the array is the number available in inventory.
I am trying to print out a table that lists all shoe sizes (even if not in the array), and then loop through to provide "number available" in inventory.
Here's what I have so far, but isn't working:
<?php
$array = array(0 => 2, 3 => 1, 5 => 1 );
print ('<table>');
print ('<thead><tr><th>Shoe Size</th>');
for ($i=3; $i<=12; $i += .50) {
print ('<th>'.$i.'</th>');
}
print('</tr></thead>');
print('<tbody><td>Total</td>');
foreach ($array as $shoe_size=>$number_in_inventory) {
for ($i=3; $i<=12; $i += .50) {
if ($i == $shoe_size) {
print('<td>'.$number_in_inventory.'</td>');
}
else {
print('<td>0</td>');
}
}
}
print("</tbody></table>");
My problem is, because I have a foreach loop AND a for loop, it is printing out twice the number of table columns (<td>'s).
How can I better adjust this code so that it only loops through and correctly displays the columns once? I am pretty lost on this one.
Many thanks!
Change your main loop to go through each possible shoe size; if the size exists in the inventory array ($array) then print that value, else print zero.
// ...
print('<tbody><td>Total</td>');
for ($i = 3; $i <= 12; $i += .50) {
if (array_key_exists("$i", $array)) {
print '<td>'.$array["$i"].'</td>';
} else {
print '<td>0</td>';
}
}
// ...
My problem is, because I have a foreach loop AND a for loop, it is printing out twice the number of table columns ('s).
That is precisely the problem. Just like with the <th> section, you want to print a <td> for each of the possible shoe sizes (3 through 12). For each possible shoe size, all you need to do is check to see whether there is a corresponding value in the inventory as my snippet above does.
You might try looping through all the sizes and then for each size, check to see if it's in the array using array_key_exists()