Explode string to array PHP - php

I have two input fields in PHP form. The fields need to be saved to array and the output should have word lenght of each words next to it in brackets. Also need to evaluate which input field 1 or 2 has longest word and how many words are in each fields. It shows error during execution. syntax error, unexpected end of file
Screenshot 1 Screenshot 2
<!DOCTYPE html ">
<html>
<head>
<meta charset="UTF-8">
<title> Two Input field compare PHP </title>
</head>
<body>
<?php
echo "<br/>";
if (isset($_POST['submit'])) {
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
//example $input1 = "Learning the PHP";
//example $input2 = "Counting words and showing(7) like this word<< ";
if (empty($input1)) {
echo "You need to enter both fields !";
}
if (empty($input2)) {
echo "You need to enter both fields !";
}
echo $input1;
echo $input2;
$inputarr1 = explode(" ", $input1);
$inputarr2 = explode(" ", $input2);
$longestlenghtarr1 = $longestlenghtarr2 = 0;
$arraylength1 = sizeof($inputarr1);
$arraylength2 = sizeof($inputarr2);
$longest1 = $longest2 = 0;
for ($x = 0; $x < arraylength1; $x++) {
echo $inputarr1[$x] . " < " . strlen($inputarr1[$x]) . " > ";
if (strlen($inputarr1[$x]) > $longest1) {
$longest1 = strlen($inputarr1[$x]);
}
}
for ($y = 0; $y < arraylength2; $y++) {
echo $inputarr2[$y] . " < " . strlen($inputarr2[$y]) . " > ";
if (strlen($inputarr2[$y]) > $longest2) {
$longest2 = strlen($inputarr2[$y]);
}
}
if ($longest1 > $longest2) {
echo "<br/> The field 1 input has longest word of lenght " . $longest1." characters !";
}
if ($longest2 > $longest1) {
echo "<br/> The field 2 input has longest word of lenght " .$longest2." characters !";
}
if ($arraylength1 > $arraylength2) {
echo "<br/> The field 1 input has more words";}
if ($arraylength2 > $arraylength1) {
echo "<br/> The field 2 input has more words";
}
echo "<br/>";
?>
<div>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
Input Text 1 <br/>
<input type="text" name="input1" /><br/>
Input Text 2 <br/>
<input type="text" name="input2" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body></html>

Probably wrong variable name - it should cause something like Undefined index 'input1' error.
Try replace $POST_ with $_POST so you should have
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];

Related

"How to have the user add two random integers on a single page using $_POST"

I am trying to create an adding game PHP and HTML, where the user guesses the sum of two random integers. However, when the user submits the answer, the integers randomize again, changing the sum and making the user's guess incorrect.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit']))
{
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I am expecting the output to be "nice, you got it right" when the $guess==$sum, but $sum changes when the form is submitted, making the 2 variables unequal.
Try to use session and store the two random number. PHP Session
just like this.
<?php
session_start();
if (isset($_POST['submit']))
{
$sum = $_SESSION['y'] + $_SESSION['x'];
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
$_SESSION['x']= (rand(1,10));
$_SESSION['y']= (rand(1,10));
echo "<br>What is " . $_SESSION['x'] . " + " . $_SESSION['y'] . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I hope I answer your problem. just read the PHP session it helps you a lot.
You can create a hidden input field to post the sum value. Then compare that value with the guessed value.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit'])) {
$guess = $_POST['guess'];
$value = $_POST['sum'];
if ($value == $guess) {
echo "nice, you got it right.";
} else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input type="hidden" name="sum" value="<?=$sum?>" />
<input name="submit" type="submit" />
</form>
You should store your $x and $y in a hidden input.
Calculate the sum by using the post value instead of generating new value.

How to do 3*3 matrix multiplication in php?

How can i do 3*3 or 3*1 matrix multiplication in php with following code. where should i have to change the logic ?????
this code completely work for only 2*2 matrix multiplication
Here is my code:
$a = Array( Array(1,2),Array(4,5));
$b = Array( Array(7,5), Array(3,2));
$sumArray = array();
$c = array();
for($i=0;$i<2;$i++)
{
for($j=0;$j<2;$j++)
{
$c[$i][$j]=0;
for($k=0;$k<2;$k++)
{
$c[$i][$j]=$c[$i][$j]+($a[$i][$k]*$b[$k][$j]);
}
}
}
echo "<pre/>";
print_r($c);
?>
Matrix Multiplication
Rules :
First matrix's column and Second matrix's row must be same
Result matrix's size will be First matrix's Row and Second matrix's Column
$a = Array( Array(1,2),Array(4,5));
$b = Array( Array(7,5), Array(3,2));
$r=count($a);
$c=count($b[0]);
$p=count($b);
if(count($a[0]) != $p){
echo "Incompatible matrices";
exit(0);
}
$result=array();
for ($i=0; $i < $r; $i++){
for($j=0; $j < $c; $j++){
$result[$i][$j] = 0;
for($k=0; $k < $p; $k++){
$result[$i][$j] += $a[$i][$k] * $b[$k][$j];
}
}
}
print_r($result);
Matrix computation is achieved by multiplying any column or row elements by their own cofactors.
Codes according to your request;
<?php
if ($_POST['hsp']) {
$de3t11=$_POST['m11']; $de3t12=$_POST['m12']; $de3t13=$_POST['m13'];
$de3t21=$_POST['m21']; $de3t22=$_POST['m22']; $de3t23=$_POST['m14'];
$de3t31=$_POST['m31']; $de3t32=$_POST['m23']; $de3t33=$_POST['m15'];
//show on screen
echo $de3t11 ." ". $de3t12. " ". $de3t13;
echo "<br>";
echo $de3t21 ." ". $de3t22. " ". $de3t23;
echo "<br>";
echo $de3t31 ." ". $de3t32. " ". $de3t33;
echo "<br>";
//calculate matrix
$m3m11=(($de3t22*$de3t33)-($de3t23*$de3t32))*(1);
$m3m12=(($de3t21*$de3t33)-($de3t23*$de3t31))*(-1);
$m3m13=(($de3t21*$de3t32)-($de3t22*$de3t31))*(1);
//Determinant
$det3t3=(($de3t11*$m3m11)+($de3t12*$m3m12)+($de3t13*$m3m13));
echo $det3t3;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="number" name="m11">
<input type="number" name="m12">
<input type="number" name="m13">
<br><br>
<input type="number" name="m21">
<input type="number" name="m22">
<input type="number" name="m23">
<br><br>
<input type="number" name="m31">
<input type="number" name="m32">
<input type="number" name="m33">
<input type="submit" name="hsp">
</form>
</body>
</html>

passing values from php to html

I want to pass values from my php code (in the same page) to my html - so I could print it out nicely
here is my php function (it's in a while cause it needs to print out 3 lines from a text)
if(sizeof($words)==1)
{
$single = new single;
$docres = $single->find($words);
$dir = "source";
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
echo fgets($handle);
//this is what i need to print in my html
$input = $_POST['input'];
$counter++;
}
}
}
}
and here is my html
<html>
<head>
<title>serach engine</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code' >
// <input type="value" name="input" value="<?php echo $input; ?>">
</center>
</form >
//I would like to print it out here
</div>
</body >
</html >
I searched over the web and saw a solution using $_POST but it didn't work for me...
You could just append it to a new variable and echo it out in the html.
For example:
while($counter < 3) {
echo fgets($handle);
//this is what i need to print in my html
$input .= $_POST['input'] . "<br />";
// You could also do:
// $input .= "<li>" . $_POST['input'] . "</li> "
// For a list item
$counter++;
}
And then echo it in the html:
</form>
<?php echo $input; ?>
</div>
Note: You did not increment your $counter in the while loop.

Form not outputting number [duplicate]

This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Thus far I have got this, it calculates the numbers but not sure how to calculate it by the letters abcd,
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
print_r($myInputs);
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
echo $myArray[$_GET['a']] + $myArray[$_GET['b']] ;
/*
if ($_GET['calc'] == "yes")
{
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$total = $a+$b+$c+$d;
print "Total is: $total <p>";
}
*/
?>
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input']; //input being passed via POST method
$expression = $_POST['expression']; //expression being passed via POST method
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression; //evaluates sum as expression
$input_letters = array(); //puts letters into a array
$input_operators = array(); //puts operators into a array
for ($i = 0; $i < strlen($expression) ; $i++) { //gets string length
if (($i % 2) == 0) {
$input_letters[] = $expression[$i]; //getting the character for the position i
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) { //size of= numbers (4)
$value = $input[$input_letters[$i]]; //takes the value from the letters
if ($i == 0) {
$sum += $value; //adds the sum if = 0
} else {
if ($input_operators[$i-1] == '+') { //checks to see if the operator is +
$sum += $value;
} else if ($input_operators[$i-1] == '-') { //checks to see if the operator is -
$sum -= $value;
}
}
print_r($value);
}
} else {
echo "Error: expression not correct form"; //error message
}
?>
<form action="" method="post"> <!--Form begins-->
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$( "form" ).submit(function( event ) {
var val_is_good=($('input[name="expression"]').val().length==4)?true:false;
if(!val_is_good){alert('Enter four letters or die!');}
});
</script>
Now I added a script to tell users if they enter more then 4 letters a alert message says please only enter four letters, would someone know why my script is outputing the alert message even when enter only four letters?
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
//you are assigning $_GET values to an array myInputs so no need here
print_r($myInputs);
echo $myInputs[0]+ $myInputs[1];
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
// In case of myarray it has keys a,b,c,d only... so need of using $_GET here also.
echo $myArray['a']+$myArray['b'];
// but if you want to it directly from$_GET values.
echo $_GET['input'][0]+ $_GET['input'][1];
?>
I found a solution at this site. Here is the code from that post:
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input'];
$expression = $_POST['expression'];
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression;
$input_letters = array();
$input_operators = array();
for ($i = 0; $i < strlen($expression) ; $i++) {
if (($i % 2) == 0) {
$input_letters[] = $expression[$i];
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) {
$value = $input[$input_letters[$i]];
if ($i == 0) {
$sum += $value;
} else {
if ($input_operators[$i-1] == '+') {
$sum += $value;
} else if ($input_operators[$i-1] == '-') {
$sum -= $value;
}
}
}
} else {
echo "Error: expression not correct form";
}
?>
<form action="" method="post">
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>

Passing array with values php

is it possible to pass through $_POST or $_GET an array, with values in it, without using serialize() and unserialize() ?
here is an example code, trying to find a number..i entered value 4 instead of rand, just to do the testing..
i thought of the potential of using a foreach to make multiple input hidden, in case i could pass all variables every single time, but it seems not to be working..
any ideas..??? or it is just not possible without serializing?
<?php
$x = $_POST['x'];
$Num = $_POST['Num'];
$first_name[] = $_POST['first_name'];
if (!$x)
{
Echo "Please Choose a Number 1-100 <p>";
$x = 4; //rand (1,4) ;
}
else {
if ($Num >$x)
{Echo "Your number, $Num, is too high. Please try again<p>";}
elseif ($Num == $x)
{Echo "Congratulations you have won!<p>";
Echo "To play again, please Choose a Number 1-100 <p>";
$x = 4;// rand (1,4) ;
}
else
{Echo "Your number, $Num, is too low. Please try again<p>";}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> <p>
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<input type = "hidden" name = "x" value=<?php echo $x ?>>
<?php
foreach($first_name as $val){
echo "<input type=\"hidden\" name=\"first_name[]\" value=$val />";
}
?>
</form>
</body>
</html>
<?php
foreach($first_name as $k => $val)
echo "<input type='hidden' name='first_name[$k]' value='$val' />";
should work.
here is the solution that i figured out...
$x = $_POST['x'];
$Num = $_POST['Num'];
$first_name = $_POST['first_name']; //creating array from the begining
$first_name[] = $Num; // add current num to next available slot in array
$counter = $_POST['counter'] +1;
if (!$x) // below this is the same..
....
....
<input type = "hidden" name = "x" value=<?php echo $x; ?>>
<input type = "hidden" name = "counter" value=<?php echo $counter; ?>> //add a counter to count loops
<?php
if ($counter>=2){ //counter in first load of page will be 1, so we need to read enter value from the next load of page
for ($i=0; $i<=($counter-2); $i++){ // counter-2 gives us the actual number of elements
echo "<input type=\"hidden\" name=\"first_name[]\" value=$first_name[$i] />";
}
}
?>
</form>

Categories