Search with count in array in php - php

<?php
$cars=array("Volvo","BMW","Toyota","abc","xyz");
?>
Hello everyone, i have following array,above is the code,How can i search and get total number of values after "BMW".please help me with the above problem.
To clarify, I want the answer 3 in this case and if the value does not exist I would like the answer 5

This would work
echo count($cars) - (array_search('BMW', $cars) + 1);
This would be a little safer, just in case the value does not exist in the array.
$cars=array("Volvo","BMW","Toyota","abc","xyz");
if ( array_search('BMW', $cars) !== FALSE ) {
echo count($cars) - (array_search('BMW', $cars)+ 1);
}else{
echo 'BMW Does not exist in the array';
}
If you want the answer 5 if the item does not exist this might be what you want
echo count($cars) - (array_search('BMWX', $cars) !== FALSE ? array_search('BMWX', $cars)+ 1 : 0);
Or to simplify
echo count($cars) - array_search('BMWX', $cars);
will also give the answer 5

Related

how to calculate the number of matches of files which have different values in php

For a multiple choice exam, i store the data in .txt files.
I have 8 .txt files in which stored 2 or more numbers. The name of the txt files are 1.txt, 2.txt, 3.txt ...
The first number in each txt file is ALWAYS the correct answer. I want to compare this first number with the last number of that txt file.
foreach($all_files as $file) {
$each_file = file_get_contents($file);
$choosen_answer = substr($each_file, -1); // last number is the number user has choosen
$correct_answer = substr($each_file, 0,1); // first number is the correct answer
// output the answers
echo '<span class="choosen_answer">'.$choosen_answer.'</span>';
echo '<span class="correct_answer">'.$correct_answer.'</span>';
$wrong = 0;
if($choosen_answer != $correct_answer) { // compare the 2 values
$wrong++;
echo '<span class="wrong text-danger">Wrong</span>';
}
else {
echo '<span class="correct text-success">Correct</span>';
}
}
echo count($wrong); // this should give me the number of wrong answers, but it does not...
I want to calculate the number of wrong answers and i tried count($wrong); for this but it does not give me the number of wrong answers.
So what i need: if 3 of the 8 questions are wrong answered, it should give me the number 3
Each txt file looks like this:
02 // 0 is the correct answer, 2 is the answer from the user. I compare 0 with 2. So wrong answer
or
14 // 1 is the correct answer. 4 is the answer of the user. I compare 1 with 4. So wrong answer
or
22 // 2 is the correct answer. 2 is also the answer of the user. So correct answer
$wrong = 0; is in the foreach loop! so after every iteration, it makes it 0 again.
Your code should look like:
$wrong = 0;
foreach($all_files as $file) {
$each_file = file_get_contents($file);
$choosen_answer = substr($each_file, -1); // last number is the number user has choosen
$correct_answer = substr($each_file, 0,1); // first number is the correct answer
// output the answers
echo '<span class="choosen_answer">'.$choosen_answer.'</span>';
echo '<span class="correct_answer">'.$correct_answer.'</span>';
if($choosen_answer != $correct_answer) { // compare the 2 values
$wrong++;
echo '<span class="wrong text-danger">Wrong</span>';
}
else {
echo '<span class="correct text-success">Correct</span>';
}
}
echo $wrong;

PHP: Declaring if a value is odd or even from a random integer [duplicate]

This question already has answers here:
Test if number is odd or even
(20 answers)
Closed 5 years ago.
I don't know where I am going wrong with my code and I am asking for some guidance as I am new to PHP.
I am trying to do an If else statement that will display if the random integer is odd or even. When I run the code it keeps on showing 'Number is odd' or nothing and I am not sure why. Any guidance will be much appreciated.
$RandomValue = rand(0, 10);
$OddValues = (1 || 3 || 5 || 7 || 9);
$EvenValues = (0 || 2 || 4 || 6 || 8 || 10);
if($RandomValue == $OddValues) {
echo $RandomValue, ' Number is odd';
} else {
if($RandomValue == $EvenValues)
echo $RandomValue, ' Number is even';
}
There is a much easier way to do this. Use the modulo operator in php which is written as %. The modulo operator essentially returns 0 if there's no remainder and the remainder if there is. In this case, you're looking to just divide by 2 and see if anything remains, that's what modulo is doing here. So the only thing it's going to return is either 0 or 1.
$x = 3;
if($x % 2 == 0) { //number is even}
else { //number is odd }
Check it like
if ($RandomValue % 2 === 0) {
echo "$RandomValue is even";
} else {
echo "$RandomValue is odd";
}
For reference, see:
http://php.net/manual/en/language.operators.arithmetic.php
https://en.wikipedia.org/wiki/Modulo_operation
You can also check using the bitwise &
$is_odd = $x & 1;
Such as this
$nums = [1,2,3,4,5,6,7,8,9,10];
foreach( $nums as $x ){
$is_odd = $x & 1;
echo $is_odd ? 'ODD' : 'EVEN';
echo "\n";
}
Output
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN
You can test it here
http://sandbox.onlinephpfunctions.com/code/d47ab3970f24038afb28876b212a6f020eb0a0aa
And for a complete answer to your question
$RandomValue = rand(0, 10);
if($RandomValue & 1) {
echo $RandomValue. ' Number is odd';
} else {
echo $RandomValue. ' Number is even';
}
PS. you also have a comma and not a . here
echo $RandomValue, ' Number is odd';
http://sandbox.onlinephpfunctions.com/code/e2573a5dfe0e5aec6c0bfac3ce62c6788b070641
And indeed we can condense this a bit more into only 2 lines
$RandomValue = rand(0, 10);
echo $RandomValue. ' Number is '.($RandomValue & 1 ? 'even' : 'odd');
Oh and if you are not sure what the & "single and" is ( or bitwise in general ):
http://php.net/manual/en/language.operators.bitwise.php
Use Modulo.
if($RandomValue % 2 === 0){ echo $RandomValue, ' Number is even'; }
you can use ternary operator and do the test in one line :
function evenOrOdd($number)
{
return 0 === $number % 2 ? 'even' : 'odd';
}

Can't echo string when used assign operator?

When I run my variable array with foreach,I have found that echo string is not display when using with addition operator.But echo only assign operator can display.What is the reason that can't echo string with using addition operator ?
<?php
$key = 3;
echo $key+1;echo "<br>"; // 4
echo "The answer is ".++$key; // The answer is 4
echo "The answer is ".$key+1; // 1
//last echo is why can't display string and not getting 4
?>
That's because you're doing a math operation with a string.
"The answer is ".$key+1 is the same as
"The answer is 3" + 1 which equals 1;
You need to use () to clearify the scope
$key = 3;
"The answer is ".($key+1) === "The answer is 4"
Also
echo "The answer is ".++$key; // The answer is 4
echo "The answer is ".($key+1); // This would be 5, beause you're incrementing $key by 1 beforehand

Random number thats not in array [duplicate]

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..

PHP keyword to convert decimal number into a number always one ahead

$val=3.1;
echo $val;
How can i get the result 4 from $val.
Use ceil
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>
Reference: http://in2.php.net/manual/en/function.ceil.php
Ceil function is what you want. Just do the following
ceil($val);
P.S. if you want it to be always an integer number that is bigger by 1 than the previous (even if the number is Integer), you can do something like this:
$a = ( ceil($val) == $val) ? ($val + 1) : ceil($val);

Categories