how to echo exploded array line - php

Here's the code.
<!DOCTYPE html>
<html>
<head><title>Numbers</title></head>
<body>
<form action="index.php" method="get">
<b>Numbers</b>
<br>
<textarea rows="12" cols="25" name="result" value="result"></textarea>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
<?php
$result=$_GET["result"];
if (empty($_GET['result']))
{
echo '<p><font size="3" color="red">Field is Empty*</font></p>';
}
elseif (isset($_GET['result']))
{
$result=(explode("\n", $result));
}
{
echo count ($result);
echo "<br />";
echo array_sum($result);
}
?>
Ok so I figured out how to get most of my assignment's tasks and the last 1 that I am stuck with is using similar codes such as filter_var to print out non-numerical values that are submitted. Ex. a b c * & ! #
PRINTING any invalid inputs that aren't numbers. Ex. Letters, symbols.
Any suggestions?

you can use the below code on your $result array & get the desired results:
$oddArray = array();
$evenArray = array();
$skippedArray = array();
foreach($result as $value)
{
if(is_numeric($value))
{
if($value%2 == 0)
{
$evenArray[] = $value;
}
else
{
$oddArray[] = $value;
}
}
else
{
$skippedArray[] = $value;
}
}
echo "Sum of odd values entered: ".array_sum($oddArray);
echo "Sum of even values entered: ".array_sum($evenArray);
echo "Skipped invalid values entered: ";
print_r($skippedArray);
I hope above will help you.

Related

Why is my if condition skipping characters?

I have made a game flames, where example given a name is Patrick and the other name is Abcdefg, the loop will crash out one character from one name that is the same with a character in the other name. When my condition is if srtlen($name1)==strlen($name2), why is my loop not crashing out letter a in the name Patrick and abcdefg? It only crashes out c.
My problem is in if($r==$e) part.
The desired outcome from the name Patrick and abcdefg is status=10; because A and C are crashed out.
<html>
<head>
<title>Flames</title>
</head>
<body>
<center><form method="post" style="margin-top:60px;">
<h2>Flames</h2>
<input type="text" name="name1" placeholder="First name"/><br>
<input type="text" name="name2" placeholder="Second name"/><br><br>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$name1=$_POST['name1'];
$name2=$_POST['name2'];
//this is if the names have space on it.
if(strstr($name1,' ')&&strstr($name2,' ')||strstr($name1,' ')||strstr($name2,' ')){
$exploded1=explode(' ',$name1);
$exploded2=explode(' ',$name2);
$joined1=implode("",$exploded1);
$joined2=implode("",$exploded2);
$e=strlen($joined2);
$r=strlen($joined1);
}
else{
$r=strlen($name1);
$e=strlen($name2);
}
$counter=0;
$same=0;
if($r>$e){
for($m=0; $m<=$e-1; $m++){
for($i=0; $i<=$r-1; $i++){
if($counter<$e){
if($joined1[$i]==$joined2[$m]){
$same++;
//$counter++;
$joined1[$i]=' ';
break;
}
}
}
}
}
elseif($e>$r){
for($m=0; $m<=$r-1; $m++){
for($i=0; $i<=$e-1; $i++){
if($counter<$r){
if($joined2[$i]==$joined1[$m]){
$same++;
//$counter++;
$joined2[$i]=' ';
break;
}
}
}
}
}
//this is where it did not check the a character which is most likely to be crashed out because it has a pair
if($r==$e){
for($m=0; $m<$r; $m++){
for($q=0; $q<$r; $q++){
if($name1[$q]==$name2[$m]){
echo $name1[$q].'<br>';
$same++;
//$counter++;
$name1[$q]=' ';
break;
}
}
}
}
$sum=$e+$r;
$mult=$same*2;
$status=$sum-$mult;
echo $joined1.'<br>';
echo $joined2.'<br>';
echo 'r'.$r; echo '<br>';
echo 'e'.$e; echo '<br>';
echo 'status'.$status; echo '<br>';
echo 'sum'.$sum;echo '<br>';
echo 'mult'.$mult; echo '<br>';
echo "$joined1 <br>";
echo "$joined2 <br>";
//this is to determine the flames status.
if($status==1||$status%6==1){
echo 'Friends';
}
if($status==2||$status%6==2){
echo 'Lovers';
}
if($status==3||$status%6==3){
echo 'Anger';
}
if($status==4||$status%6==4){
echo 'Marriage';
}
if($status==5||$status%6==5){
echo 'Enemy';
}
if($status==6||$status%6==0){
echo 'Soulmates';
}
}
?>
</center>
</body>
</html>
When you compare Patrick and Abcdefg , c will only match as capital A and small a are different ,so to solve this you can convert your names to lowercase and then compare them .i.e :
$name1=strtolower($_POST['name1']);
$name2=strtolower($_POST['name2']);
Output :
a<br>c<br>patrick<br>abcdefg<br>r7<br>e7<br>status10<br>sum14<br>mult4<br>patrick <br>abcdefg <br>Marriage

Store post form values in hidden input array

I'm new to php and here's my code for a number guessing game. Since I don't know how to define a random number, I chose the number myself, 80. I'm trying to store all the guesses prior to the right one, and after the right guess, print them out on the screen. But I can't seem to be able to get it right since it only prints only the last guess before the right one.
Any help is appreciated!
<html>
<head>
</head>
<body>
<?php
$allguesses = array();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_POST["tmn"] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
array_push($allguesses,$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
foreach($allguesses as $x){
echo "<input type ='hidden' name = 'tmn[]' value=' ".$x . " '>";
}
?>
</form>
</body>
</html>
Sessions seem the best for where you are in your learning curve.
The session allows the normal stateless http protocol to remember things between each submission of a form or forms. So we will save each guess in an array of guesses in the SESSION, which in PHP is an array as well.
<?php
session_start(); // create a session, or reconnect to an existing one
if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["guess"]) ) {
$_SESSION['guesses'][] = $_POST["guess"]; // keep an array of guesses
// $t = $_POST["guess"]; no need for extra variables on the stack
$sayi = 80;
if($sayi > $_POST["guess"]){
echo 'Guess higher';
}elseif($sayi == $_POST["guess"]){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_SESSION['guesses'] as $guess){
echo $guess . ',';
}
$_SESSION['guesses'] = array(); // clear the old guesses out
}else{
echo 'Guess lower';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Removed uneeded codes.
Changed method of showing previous guesses with the below code.
echo implode( ", ", $_POST["tmn"] ); // cleaner
This block handles storing previous guesses into an array that is used for displaying previous guesses.
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
Fixed previous version of below block of code so that hidden <inputs> of previous guesses are outputted properly..
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
Updated Code:
<html>
<head>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
echo implode( ", ", $_POST["tmn"] );
}else{
echo 'Guess lower';
}
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
</form>
</body>
</html>
For random numbers you can use rand($min, $max). to store the guesses you can use the global variable $_SESSION.
<html>
<head>
</head>
<body>
<?php
//start session (needed to use the $_SESSION variable)
start_session();
if($_SERVER["REQUEST_METHOD"] == "POST"){
//if empty -> initalize array
if (empty ($_SESSION['allguesses']){
$_SESSION['allguesses'] = array ()
}
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
//echo all guesses from $_SESSION variable
foreach($_SESSION['allguesses'] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
//push in $_SESSION variable
array_push($_SESSION['allguesses'],$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

Get session array from different file

I can't access array from other file and still don't figure it out, whether my data already stored into array or not. Should i put $_SESSION into the function?
Lat3_3a.php
<form id="form1" name="form1" method="post" action="Lat3_3b.php">
Insert number: <input type="number" name="num" id="num" />
<input type="submit" name="button" id="button" value="OK" />
</form>
Lat3_3b.php
<?php
session_start();
$_SESSION["num"] = $_POST["num"];
if (empty($_SESSION["num"]))
echo "Please, insert number";
else {
$val=$_POST['num'];
echo " Factorial " .$val. " ! = " .factorial($val)."<br/>";
echo "<a href='Lat3_3c.php'>Link</a>";
}
function factorial($val){
if($val<=1){
$result=1;
return $result;
}elseif($val>1){
for($i=1; $i<=$val; $i++){
$result=$val * factorial($val-1);
}
return $result;
}
$data=array($val,$result,"12345", "Travis");
$_SESSION["var"]=$_POST["data"];
}
?>
Lat3_3c.php
<?php
session_start();
if(empty($_SESSION["var"]))
echo "Variable not found";
else
echo "Data : ". $_SESSION["var"];
?>
Ok looking a bit more in to your code, you need to learn more about the session, post and functions. For that a look at the PHP manual site.
Site http://php.net
For your code to work you need to use something like this:
<?php
session_start();
$_SESSION["num"] = $_POST["num"];
$_SESSION["var"]=array();
if (empty($_SESSION["num"])){
echo "Please, insert number";
}
else {
$val=$_POST['num'];
$function_result=factorial($val);
$data=array($val,$function_result,"12345","Travis");
$_SESSION["var"]=$data;
echo " Factorial " .$val. " ! = " .$function_result."<br/>";
echo "<a href='Lat3_3c.php'>Link</a>";
}
function factorial($val){
if($val<=1){
$result=1;
return $result;
}elseif($val>1){
for($i=1; $i<=$val; $i++){
$result=$val * factorial($val-1);
}
return $result;
}
}
?>
I'm not looking into your math.

Best Solution for this array

I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end

I have the following string in a text file:

I have a code but is not working, I'm trying use explode but still not working.
My code have two strings:
^#^b = (on)
^A^b = (off)
I try to get only 2 characters from a .txt file in a variable like:
$on=^#
$off=^A
then I can use the result to verify the state of light using a dimmer.
Code
<?php
if(isset($_POST['estado'])) {
exec('/var/www/www.rfteste.com/htdocs/estado.sh');
}
if(isset($_POST['ligar'])) {
exec('/var/www/www.rfteste.com/htdocs/liga.sh');
}
if(isset($_POST['desligar'])) {
exec('/var/www/www.rfteste.com/htdocs/desliga.sh');
}
echo "<H3>CONTROL PANEL</H3>";
$str = file_get_contents("/var/www/www.rfteste.com/htdocs/estado.txt");
$vals = explode("^", $str);
$num1 = "^".$vals[0];
$num2 = "^".$vals[1];
$onoff= "^A";
if($num2 == $onoff)
echo "<b>on</b>";
else
echo "<b>off</b>";
?>
<html>
<body>
<form method="post" action="">
<p>
<center><input type="submit" value="Ligar" name="ligar""';" /></center>
<center><input type="submit" value="desligar" name="desligar""';" /></center>
<center><input type="submit" value="atualizar" name="estado""';" /></center>
i think this can help you solve your problem
function checktext($text){
if(preg_match("'#'", $text)){
return 'on';
}else{
return 'off';
}
}
echo checktext('^A^b');
Use php substr()
if(substr($str, 0, 1) == "A")
{
echo "<b>on</b>";
} else {
echo "<b>off</b>";
}

Categories