This question already has answers here:
What is the most efficient way to count all the occurrences of a specific character in a PHP string?
(4 answers)
Closed 5 years ago.
I am trying to separate 2 symbols from a string and then
count how many of these symbols there are.
So if i had : 1110001110000
Then it should find that there are 6= 1's and 7= 0's
So This is what I have tried:
Essentially what I need, is to read the string indexes in code would be string[$i] then IF there is a 1 or a 0 count it.
I tried using a for-loop
for ($i=0; $i < $getInput[$i] ; $i++) {
if ($getInput[$i] == 1) {
echo "ONE";
} elseif ($getInput[$i] == 0) {
echo "ZERO";
}
}
Here im trying to echo out ONE for everytime ther is a 1 and ZERO for everytime theres a zero.
$counter = 0;
foreach ($getInput as $key) {
echo $key;
}
here i tried to utilize a foreach, here I am not really declaring to see for One index, i tried putting a for each in a for but needless to say, it didn't work.
Using substr_count, you can do this in a fairly straightforward way:
echo substr_count("1110001110000", '1'); //Echos 6
echo substr_count("1110001110000", '0'); //Echos 7
Substr_count.
http://php.net/manual/en/function.substr-count.php
$str = "1110001110000";
Echo "there is " .substr_count($str, "0") ." zeros \n";
Echo "there is " .substr_count($str, "1") ." ones \n";
https://3v4l.org/BQEiR
If you want to output it as your code implies (one one one zero) you can use numberformatter.
Here I split the string to an array and loop through it and output the spellout of each number.
$str = "1110001110000";
$arr = str_split($str);
$nf = new NumberFormatter("en", NumberFormatter::SPELLOUT);
Foreach($arr as $numb){
echo $nf->format($numb) . " ";
}
Output:
one one one zero zero zero one one one zero zero zero zero
https://3v4l.org/nHX59
Related
This question already has answers here:
Adding 2 to a variable each time
(5 answers)
Closed 1 year ago.
So I'm trying to make it so the computer counts up to ten by two and making a new line each time. When I tested this my entire computer crashed. What's wrong with it?
<?php
$test = 0;
while ($test < 10) {
$test + 2;
echo $test . "/n";
}
?>
Change:
$test + 2;
to:
$test += 2;
Currently, $test is always 0 in your code, since you are not assigning a new value to it, hence the infinite loop.
Additionally, you would also want to change:
echo $test . "/n";
to:
echo $test . "\n";
Since you need to use a backslash to indicate a new line character.
N.B. In PHP you can also use the PHP_EOL constant to indicate the end of a line.
Here you just sum $test with 2 but did not assign it back to $test
$test + 2;
Trying replace it by $test += 2;
Another point is /n is not "making a new line" as you expected, change it to \n instead.
Although you can use while statement, this is a good case to use for instead.
for($i=0; $i < 10; $i += 2)
{
echo $i . PHP_EOL;
}
Usually while is used to evaluate something every loop, some variable that can change inside the while, like a bool variable or an "infinite" loop until break.
When you have a already defined number of loops, for is usually a better approach.
This question already has answers here:
PHP counter increment in a while loop
(5 answers)
Closed 2 years ago.
i am having some issues with my php code. what i wish to add numbers like before every lines something like below
1. some data
2. some more data
what i have tried doing is like below but it would not multiply the numbers like i want it to, it only prints 1
$num = 1;
$tdetails = $num++. str_replace(',', '<br />', $row['travellers_details']);
Could someone please show how to achieve what i am looking for?
thanks
You need to iterate and increment num each time. You can store the elements in an array first using explode:
$num = 1;
$tdetails = explode(',', 'some data, some more data');
$str = "";
for($i = 0; $i < count($tdetails); $i++)
$str .= $num++ . ". ". $tdetails[$i] . "<br>";
echo $str;
Output:
1. some data
2. some more data
You can make use of HTML ol(ordered list) tag which will automatically do the numbering for you.
<?php
$tdetails = "<ol><li>" . implode("</li><li>", explode(",",$row['travellers_details'])) . "</li></ol>";
echo $tdetails;
This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 5 years ago.
I am getting o/p like "11111" and I want to sum all these digits that should become 5. But if I use count count it is showing one only i.e, 1.Rather it should show 5.
Below is my code,
$count = count($inventory['product_id']);
$product_total = $count;
echo $product_total;//o/p => 1.
I need echo $product_total;//o/p => 5.
You can use the following using str_split to get an array with all characters (in your case digits) and using array_sum to get the sum of all the digits:
$digits = "11112";
$arrDigits = str_split($digits);
echo array_sum($arrDigits); //6 (1 + 1 + 1 + 1 + 2)
Demo: https://ideone.com/tZwi9J
Count is used for counting array elements.
What you can do in PHP, is to iterate over a string using either a foreach (not 100% sure) or for loop for this and accessing the elements like array elements by their index:
$str = '111111123545';
$sum = 0;
for ($i = 0; $i < strlen($str); $i++) {
$sum += intval($str[$i]);
}
print $sum; // prints 26
Alternativly, you can split the string using no delimiter and using the array_sum() function on it:
$str = '111111123545';
$sum = array_sum(str_split($str));
print $sum; // prints 26
array_sum(str_split($number));
Another possible way to count the list of digits in PHP is:
// match only digits, returns counts
echo preg_match_all( "/[0-9]/", $str, $match );
// sum of digits
echo array_sum($match[0]);
Example:
$ php -r '$str="s12345abas"; echo "Count :".preg_match_all( "/[0-9]/", $str, $match ).PHP_EOL; echo "Sum :".array_sum($match[0]).PHP_EOL;'
Count :5
Sum :15
This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 7 years ago.
I would like to Increment numbers with double digits if the number is less then 10
This is what i tried so far
$i = 1;
echo $i++;
results is 1,2,3,4,5,6 so on
Then i try adding a condition
$i = 1;
if ($i++<10){
echo "0".$i++;
}else{
echo $i++;
}
Work but skipping the numbers 2,4,6,8 so on.
Can anyone tell me the proper way to do this?
If the condition is only there for the leading zero you can do this much easier with this:
<?php
$i = 10;
printf("%02d", $i++);
?>
if you want prepend something to a string use:
echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.
Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.
Keep it simple:
// Increment $i
$i ++;
// Format it for display
if ($i < 10) {
$text = '0'.$i; // Prepend values smaller than 10 with a zero
} else {
$text = $i;
}
// Display it
echo($text);
<?php
$i = 1;
for($i=1;$i<15;){
if($i<10){
echo '0'.$i++."<br>";
}else{
echo $i++."<br>";
}
}
?>
This question already has an answer here:
PHP how to get a random number that is different from values of an array
(1 answer)
Closed 7 years ago.
I have an array of numbers and I need to make a random number then check if that number is not in the array, If it is make another random number and then check that number to see if its in the array.
example.
array = 1, 2, 4, 5, 7
rand(1, 7) = 3 or 6
if rand(1, 7) = 1, 2, 4, 5 or 7 it would run again until it returned 3 or 6.
anyone know how to do this in php?
You may simply generate a random number and check if it is already in the array
$in = [1, 4, 7, 9];
do {
$rand = rand($min, $max);
} while(in_array($rand, $in));
echo $rand, ' is random, but not in the input array';
The above code generates a random integer that is insides the bounds defined in $min and $max. If the value already exists inside the array a new random value is fetched and compared to the input array.
Note: While the above is the minimal working code you may create an endless loop if your input array contains all possible values(Thanks #Action Dan). You didn't state in your question whether this is possible or not. If it is possible you need to work around this. Either by limiting the the maximum tries or validating the input array before and issuing an error message or increasing the 2nd parameter of rand.
Example(validating, only recommended for smaller arrays):
$in = [1,2,3,4,5];
$min = 1;
$max = 5;
if(range($min, $max) === $in) {
echo 'No possible value in range';
exit;
}
// code from above
<?php
$numbers = array(1,2,3,4,5,6,7);
$rand = rand(1,10);
if (in_array($rand, $numbers))
{
echo "Match found";
}
else
{
echo "Match not found";
}
echo "<br />" . $rand;
?>
In this sample I had $rand intentionally have more than 7, just to make sure the code is working well and "Match not found" is printed..
in_array() function checks if the value of $rand exists in $numbers if true.. prints "Match found" if not prints "Match not found".
Hope this helps..