Count and read multiple input in one text field [duplicate] - php

This question already has answers here:
php count the number of strings after exploded
(5 answers)
Closed 8 years ago.
I need to create a text field that can get multiple input like this...
1, 2, 3, 4
Then the output should be...
Number of input: 4
Mean: 2.5
The problem is how can I count the number of the input, I mean how the program know that how many input that user type into the text field, and use each value to calculate a summation for all. Does anybody has any methods or any idea?
Thanks.

Use explode(); and explode all the commas (,). That will give you an array.
From there, use count and a loop for counting and get the mean. Use trim() aswel for getting rid of empty spaces.

You can test the code here: http://writecodeonline.com/php/
$input = "1, 2, 3, 4";
//remove all whitespace
$input = str_replace(' ', '', $input);
//turn the string into an array of integers
$numbers= array_map('intval', explode(',', $input));
//the number of elements
$count = count( $numbers );
//sum the numbers
$sum = array_sum( $numbers );
//print the number of inputs, a new line character, and the mean
echo "Number of inputs: $count\r\n";
echo 'Mean: ' . $sum / $count;

Related

Replace repeating value with zero in PHP string

The following is the code
<?php
$id ="202883-202882-202884-0";
$str = implode('-',array_unique(explode('-', $id)));
echo $str;
?>
The result is
202883-202882-202884-0
for $id ="202883-202882-202882-0";, result is 202883-202882-0
I would like to replace the duplicate value with zero, so that the result should be like 202883-202882-0-0, not just remove it.
and for $id ="202883-0-0-0";, result should be 202883-0-0-0. zero should not be replaced, repeating zeros are allowed.
How can I archive that?
More info:
I want to replace every duplicate numbers. Because this is for a product comparison website. There will be only maximum 4 numbers. each will be either a 6 digit number or single digit zero. all zero means no product was selected. one 6 digit number and 3 zero means, one product selected and 3 blank.
Each 6 digit number will collect data from database, I dont want to allow users to enter same number multiple times (will happen only if the number is add with the URL manually.).
Update: I understand that my question was not clear, may be my English is poor.
Here is more explanation, this function is for a smartphone comparison website.
The URL format is sitename.com/compare.html?id=202883-202882-202889-202888.
All three numbers are different smartphones(their database product ID).
I dont want to let users to type in the same product ID like id=202883-202882-202882-202888. It will not display two 202882 results in the website, but it will cause some small issues. The URL will be same without change, but the internal PHP code should consider it as id=202883-202882-202888-0.
The duplicates should be replaced as zero and added to the end.
There will be only 4 numbers separated by "-".
The following examples might clear the cloud!
if pid=202883-202882-202889-202888 the result should be 202883-202882-202889-202888
if pid=202883-202883-202883-202888 the result should be 202888-0-0-0
if pid=202883-202882-202883-202888 the result should be 202883-202882-202888-0
if pid=202882-202882-202882-202882 the result should be 202882-0-0-0
I want to allow only either 6 digit numbers or single digit zero through the string.
if pid=rgfsdg-fgsdfr4354-202883-0 the result should be 202883-0-0-0
if pid=fasdfasd-asdfads-adsfds-dasfad the result should be 0-0-0-0
if pid=4354-45882-445202882-202882 the result should be 202882-0-0-0
It is too complicated for me create, I know there are bright minds out there who can do it much more efficiently than I can.
You can do a array_unique (preserves key), then fill the gaps with 0. Sort by key and you are done :)
+ on arrays will unify the arrays but prioritizes the one on the left.
Code
$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_unique($array) + array_fill(0, count($array), 0);
ksort($result);
var_dump(implode('-',$result));
Code (v2 - suggested by mickmackusa) - shorter and easier to understand
Fill an array of the size of the input array. And replace by leftover values from array_unique. No ksort needed. 0s will be replaced at the preserved keys of array_unique.
$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_replace(array_fill(0, count($array), 0), array_unique($array));
var_export($result);
Working example.
Output
string(17) "0-1-0-3-0-0-0-5-0"
Working example.
references
ksort - sort by key
array_fill - generate an array filled with 0 of a certain length
This is another way to do it.
$id = "202883-202882-202882-0-234567-2-2-45435";
From the String you explode the string into an array based on the delimiter which in this case is '-'/
$id_array = explode('-', $id);
Then we can loop through the array and for every unique entry we find, we can store it in another array. Thus we are building an array as we search through the array.
$id_array_temp = [];
// Loop through the array
foreach ($id_array as $value) {
if ( in_array($value, $id_array_temp)) {
// If the entry exists, replace it with a 0
$id_array_temp[] = 0;
} else {
// If the entry does not exist, save the value so we can inspect it on the next loop.
$id_array_temp[] = $value;
}
}
At the end of this operation we will have an array of unique values with any duplicates replaced with a 0.
To recreate the string, we can use implode...
$str = implode('-', $id_array_temp);
echo $str;
Refactoring this, using a ternary to replace the If,else...
$id_array = explode('-', $id);
$id_array_temp = [];
foreach ($id_array as $value) {
$id_array_temp[] = in_array($value, $id_array_temp) ? 0 : $value;
}
$str = implode('-', $id_array_temp);
echo $str;
Output is
202883-202882-0-0-234567-2-0-45435
This appears to be a classic XY Problem.
The essential actions only need to be:
Separate the substrings in the hyphen delimited string.
Validate that the characters in each substring are in the correct format AND are unique to the set.
Only take meaningful action on qualifying value.
You see, there is no benefit to replacing/sanitizing anything when you only really need to validate the input data. Adding zeros to your input just creates more work later.
In short, you should use a direct approach similar to this flow:
if (!empty($_GET['id'])) {
$ids = array_unique(explode('-', $_GET['id']));
foreach ($ids as $id) {
if (ctype_digit($id) && strlen($id) === 6) {
// or: if (preg_match('~^\d{6}$~', $id)) {
takeYourNecessaryAction($id);
}
}
}

Remove duplicate comma separated values from mysql [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 2 years ago.
How can I remove duplicate comma separated values returned from database?
I have it in this format:
XL,L,XXL
XL
M,L,XL
L,XL,M
What I tried:
$new_str = array_unique(array_map('trim', explode(',', $srow['size'])));
$string = implode(',', $new_str);
But I still get duplicate values. Is there a better way of doing it?
Since your data is stored as comma separated values in the database, you will need to aggregate all the values as you loop over fetching from the database and then remove duplicates e.g.
while ($srow = $result->fetch_assoc()) {
$sizes[] = $srow['size'];
// do other stuff with fetched data
// ...
}
$sizes = array_unique(array_map('trim', explode(',', implode(',', $sizes))));
sort($sizes);
$string = implode(',', $sizes);
Demo on 3v4l.org (with simulated database fetch)

Merge Arrays But Join Corresponding Keys [duplicate]

This question already has answers here:
Transpose multidimensional array and join values with commas [duplicate]
(2 answers)
Closed 10 months ago.
I am trying to achieve the following functionality:
There is 5 textareas, the user inputs several words on different lines into the textarea, on click of a button it creates arrays from these textareas and the merges the array whilst appending the corresponding keys.
Textarea 1:
example 1
example 1 other
Textarea 2:
example 2
example 2 other
Using:
$col1 = $_POST['txta1']; $col1Array = explode("\n", str_replace("\r", "", $col1));
$col2 = $_POST['txta2']; $col2Array = explode("\n", str_replace("\r", "", $col2));
This will now give me an array for each keyword, separating the textarea value based on a new line.
I now want to combine the 2 arrays so that key [0] appends the first array and so on, it should become
array([0]=>'example 1 example 2',[1]=>'example 1 other example 2 other');
In order for me to the echo out into another textarea, the results whilst should be:
example 1 example 2
example 1 other example 2 other
You can pass both the arrays to array_map to pivot them into the format you want, then implode the inner arrays so you end up with an array of strings rather than an array of arrays.
$result = array_map(
function(...$row) { return implode(' ', $row); },
$col1Array, $col2Array
);

Easy way to parse array values [duplicate]

This question already has answers here:
Applying a function for each value of an array
(5 answers)
Closed 6 years ago.
Is there util that parses array content without the need of iterating it and parsing each value?
input: ['2','3','7']
output: [2, 3, 7]
This obviously iterates internally, but you don't have to code an iterator:
$output = array_map('intval', $input);
Maps every value in $input to the intval() function and returns the result. For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.
I can't tell if you want to remove 0 values or not from your comment, but if so:
$output = array_filter(array_map('intval', $input));
You can use array_map
array = ["2","3","4"];
$intArray = array_map('intval', $array);

PHP - counting an imploded array

I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2
My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);
implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);
Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.

Categories