Simple php Calculation function dosent get called? - php

User submits a number (Temperatur in Fahrenheit)
My Code takes the user number ,converts to celsius and then outputs it.
unfortunately it dosent output :)
i did echo the user input - that works, but my output in celsius is displayed as 0
<?php
$tempInCelsius = 0;
$temp = $_GET['temp'];
function tempcalc($a){
global $tempInCelsius;
($a - 32) * 5/9;
return $placeholder;
};
tempcalc($temp);
echo $placeholder;
print "<br>";
echo $temp;
?>
Any Idea?

Here is the answer. i messed up my brain at the beginning but figured it out myself at the end.
$temp = $_GET['temp'];
function tempcalc($num1)
{
$out = round(($num1 - 32) * (5 / 9));
echo $out;
}

Related

Function doesn't return value in recursive function php [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I'd like to return some value using a recursive function. Unfortunately the function doesn't return anything until I change return to echo.
Here is a similar function I created for better understanding.
function debug($a, $i) {
$a .= $i;
if ($i !== 5) {
$i++;
debug('echo', $i);
} else {
return $a; // expecting echo5 (echo works perfectly)
}
}
echo debug('echo', 0); // doesn't return anything
Just return the value from the recursive call in order to catch the result.
EDIT:
Here is a new way of handling your code.
If the number you are passing is greater than five then subtract 1
every recursive call.
If the number is lower than five than add 1 every recursive call.
Otherwise it returns 5.
So when it reaches five, the output will be for example echo012345 or echo98765.
If you want to limit the output to echo5, then you should wrap $a .= $i with an if statement to check if ($i == 5).
<?php
function debug($a, $i) {
$a .= $i;
if ($i > 5) {
$i--;
return debug($a, $i);
} elseif ($i < 5) {
$i++;
return debug($a, $i);
}
return $a;
}
echo debug('echo', 10);
?>
The function is working 100% as intended. You do not print the value simply because the function is "returning" it. If you want the value printed, then you must echo it as you've observed yourself.
Think of it this way:
Return - returns the value in raw data.
echo - prints stuff.
Also the way your recursive function works now, it only contains the return value within its scope, so the value is "dropped" when the execution is completed. That's why you won't be able to echo anything. When you echo inside the function, it's echoing the value before stopping the execution.
One way to circumvent this, is by adding a print parameter to the function if you wish for your value to be printed,
Example:
function debug($a, $i, $print=false) {
$a .= $i;
if($i < 5) {
$i++;
debug('echo', $i, $print);
} else{
if($print){
echo $a;
}
return $a;
}
}
debug('echo', 0, true);

How to convert $_SESSION['myarray'] to regular PHP array

So I have declared a Session array and initialized it with zeroes. It's basically a multidimensional array. However, I'm thinking of converting it to a regular array because everytime I test whether a value exists or not using the in_array() function, it fails. It keeps adding existing values.
<?php
session_start();
$_SESSION['numbers'] = array(
array(0,0,0,0,0), //row1
array(0,0,0,0,0), //row2
array(0,0,0,0,0), //row3
array(0,0,0,0,0), //row4
array(0,0,0,0,0) //row5
);
?>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$userInput = $_POST["num"];
for($r = 0; $r<sizeof($_SESSION['numbers']); $r++){
for($c = 0; $c<sizeof($_SESSION['numbers']); $c++){
$colVal = $_SESSION['numbers'][$r][$c];
insertInputAt($r,$c,$userInput);
}
}
}
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
?>
If I enter lets say 5, it inserts the input 5 to all rows and columns. I get 25 echos of value of 5 even if I put a !in_array() condition
I thought maybe if I parse the $_SESSION['numbers] as a regular array within the insertInputAt() method, the !in_array() condition might work accurately.
Thank you.
Modify your insertInputAt function to this:
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'][$row])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
First of all, you do not need to initialize $_SESSION['numbers'].
<?php
session_start();
$userInput = $_POST["num"] = 1;
for($r=0;$r<count($_SESSION['numbers']);$r++){
$found = 0;
for($c=0;$c<count($_SESSION['numbers'][$r]);$c++){
if(($_SESSION['numbers'][$r][$c]==0)&&(myfunction($_SESSION['numbers'],$userInput)==0)){
$_SESSION['numbers'][$r][$c] = $userInput;unset($_POST['num']); $found=1;break;
}
}
if($found==1)break;
}
function myfunction($array,$value){
foreach($array as $q){
if(!in_array($value,$q)){
for($i=0;$i<count($q);$i++){
if($q[$i]==0) return false;
}
}
}
}
echo "<pre>";print_r($_SESSION['numbers']);
?>

PHP and Array_round spiteful function

I'm trying to create a function to pick up words from a text file randomly, and no one here poblema. The problem arises when I try to verify if the user correctly inserts the words. Unfortunately, I always get a negative answer. From what I understood when called, the function can not save the contents into the variable that naturally remains empty.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
echo $word[$randomword];
}
}
$a = random_word();
echo "-----------------";
echo $a;
?>
If I try to check the $a variable it tells me that it is NULL. I'm sure the problem is the function but I know PHP shortly and I'm struggling to find the error.
You need to return something. Not sure if you want to return a string or an array but your code seems to be made for string.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
$returner .= $word[$randomword] . " ";
}
return trim($returner);
}
$a = random_word();
echo "-----------------";
echo $a;
?>

Generating a random string based on previous string

Okay so I'm trying to make a system where I can call:
echo _stringClamp("string");
it pushes "string" & the random string(needs to be a new random string each refresh) to an array, and if I call it twice
echo _stringClamp("string");
echo _stringClamp("string");
it will echo the same value.
This is what I have so far.
<?php
function _stringClamp ($string){
$stringSave = $string;
$stringChars = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
$strings = array();
$string = str_shuffle($string);
$string = "__" . $string;
$id = end($strings);
for ($i = 0; $i < 15; $i++) {
$string.= $stringChars[rand(0, strlen($stringChars) - 1)];
}
$strings[$stringSave] = $stringSave;
if (in_array($stringSave, $strings)) {
return $strings[$string];
}else{
$strings[$stringSave] = $string;
print_r($strings);
}
}
echo _stringClamp("IDs");
echo "<br>";
echo _stringClamp("IDs");
?>
In order to get what you are asking for you would probably need to have a random value generated before you call the function then use that random value as a second parameter such as:
<?php
$num = rand(0, 100000);
echo _stringClamp("string", $num);
echo _stringClamp("string", $num);
?>
This would provide a random number to use in your function but if you refresh the page the number will change. However if called twice on the same page it would have the same output value.... Right?
You could even use a randomly generated string instead of a number...
If i understand you correctly, you need to use hash-functions (guarantee same output for same input).
Just hash the current time.
$Seed = time();
$RandomString = md5($Seed);
If you don't want to string to be predictable (eg knowing when the script ran could let someone predict the string) then use a random number generator...
$Seed = rand();
$RandomString = md5($Seed);
As long as the variable is declared somewhere outside the function...
$RandomString = md5(time());
function _stringClamp($String) {
global $RandomString;
return $String . $RandomString;
}
You should get the same string every time

How to put random number in array and showing this array in php

Recently I made a program to create 4 random numbers I want to put these numbers in an array but I did not echo the array's numbers :
my code is:
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[i] = rand_num_generator();
}
echo $number[2];
?>
Here i am not able to access array using their index values.
You missed the $ sign in front of the i inside $number[i] which must be used before a variable
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
//print_r($number);to see the whole array
You only echo once: at echo $number[i];, $i is 4, hence you only display the last random number.
You could loop on your array to echo each.
Put your echo into loop. And you have some mistakes. Use that:
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
$number[$i] = rand_num_generator();
echo $number[$i].'<br>';
}
To put something in an array I recommend to use array_push
<?php
$numbers = array();
function rand_num_generator() {
return rand(1000,9999);
}
for($i=0;$i<4;$i++) {
array_push($numbers, rand_num_generator());
}
print_r($numbers); //Or use 'echo $numbers[0] . " " . $numbers[1]' etc etc
?>

Categories