Value outside of function is different from value inside function - php

In this elementary code, I check if a record exists with a particular itemId for a particular user and country.
The record returns 1 inside the function, but when it's outside, it's something totally different.
function recordExists(&$d) {
global $conn, $userId, $userCountryCode;
$sqlFindRecord = "select count(itemId) as recordCount from onr_items_mod where itemTempId = :itemTempId and itemStatus IN(0,5,8) and itemPublishedStatus = 2 and itemUserId = :userId and itemUserCountryCode = :userCountryCode";
$countRecord = $conn->prepare($sqlFindRecord);
$countRecord->execute(array(
":itemTempId" => $d,
":userId" => $userId,
":userCountryCode" => $userCountryCode
));
$countRecord->bindColumn('recordCount',$d);
echo 'This is D '.$d.' ---';
$row = $countRecord->fetch();
if($d == 0) {
return $d;
} elseif ($d == 1) {
return $d;
} else {
return false;
}
}
$d = 'US01'
if(recordExists($d) == 0) { //If the function returned 0
echo $d;
echo 'Was Zero';
} elseif (recordExists($d) == 1) { //If the function returned 1
echo $d;
echo 'Was One';
} else {
echo $d;
echo 'Neither Zero or One';
}
After I do the above, it's always 'Neither Zero or One'. Why is this? I tried the entire morning, but just cannot figure a way to sort this out.
This works, but not the above
function counter(&$a) {
if($a == 0) {
return $a;
} elseif ($a == 1) {
return $a;
} else {
return false;
}
}
$a = 1;
if(counter($a) == 0) {
echo $a;
} elseIf (counter($a) == 1) {
echo $a;
} else {
echo 'Umm...'.$a;
}

It will always be 'Neither Zero or One' why? Let's seee how it works
1. $d = 'US01'
2. if(recordExists($d) == 0) { //If the function returned 0
3. echo $d;
4. echo 'Was Zero';
5. } elseif (recordExists($d) == 1) { //If the function returned 1
6. echo $d;
7. echo 'Was One';
8. } else {
9. echo $d;
10. echo 'Neither Zero or One';
11. }
First $d is equal US01. It's ok. But after pass line #2 $d == 1 because you have set it in function (you have pass $d by reference).
So if statement in #2 line will return false beacuse thera are some records in database with itemTempId = 'US01'.
But now in the second if statement in line #5 variable $d = 1. So I suposse that you don't have any record with that itemTempId in your database. So the second statement (line #5) will also return false.
In my opinion you shouldn't pass it by reference.
EDIT
If you want to check if item exist in databse then yopu can ask only once. I really don't know what your goal is. But maybe this will be good
$d = 'US01';
$ret = recordExists($d);
if ($ret === 0) {
echo 'Was zero';
} elseif ($ret === 1) {
echo 'Was one';
} else {
echo 'Something else';
}

try to insert that into session variable and retrieve it in another method.
Hope it'll help.

Related

Running same code in different conditions in PHP

I am trying to reduce/simplify the following code as it looks to have repeated elements:
<?php
if ($condition == true) {
if ($a > $b*0.5) {
echo "successful";
}
else {
echo "missed";
}
}
else {
if ($a > $b) {
echo "successful";
}
else {
echo "missed";
}
}
I don't want to use functions because if I did, I would have to define all the database things again.
<?php
if ( (condition1 && ($a > $b*0.5)) || (!condition1 && ($a > $b)) ) {
echo "successful";
else {
echo "missed";
}
?>
Your Code is missed Two (Semicoloumns)}.
Try By this
<?php
$a == 2;
$b == 4;
if ($a == 2 && $a > $b*0.5) {
echo "Suuccess";
}elseif($a != 2 && $a > $b){
echo "Suuccess";
}else{
echo "Fails";
}
In order to simplify your conditions, if the output is boolean (so only two outcomes possible) you could go with either one as default and only change it to the other depending on your decisions.
<?php
$outcome = false;
if($condition1 && ($a > ($b * 0.5))) {
$outcome = true;
}
else if($a > $b) {
$outcome = true;
}
if($outcome) {
echo "succesful";
}
else {
echo "missed";
}
This also combines the technique proposed by Sofyan Thayf to use boolean operators to merge conditions.
Another approach is to put the condition into a function and return early if succesful and have a missed fallthrough like
<?php
function decide($a, $b, $condition1) {
if($condition1 && ($a > ($b * 0.5)))
return true;
if($a > $b)
return true;
return false;
}
if(decide($a, $b, $condition1)) {
echo "succesful";
}
else {
echo "missed";
}
Both approaches enable you to extract the "same code" (being the echo) and IMHO add to readability and extensibility.
<?php
$factor = $condition ? 0.5 : 1;
if ($a > $b * $factor) {
echo "Hit";
}
else {
echo "Miss";
}
Could be further reduced using two ternary operators:
echo $a > $b * ($condition ? 0.5 : 1)
? 'Hit'
: 'Miss';
Ternary operators are useful shorthand for if/else conditionals.

random color creation without change on page refresh

get data list from the database:
foreach ($rowset as $key => $value)
{
$colorrange=str_split($value->id);
$findend=end($colorrange);
$response[$key]['color'] = $this->get_color($findend);
}
function to get color:
public function get_color($findend){
if($findend == 0){
return '#455C4F';
}
elseif($findend == 1){
return '#CC5543';
}
elseif($findend == 2){
return '#4A572C';
}
elseif($findend == 3){
return '#6E352C';
}
elseif($findend == 4){
return '#E34819';
}
elseif($findend == 5){
return '#283811';
}
elseif($findend == 6){
return '#0E2F44';
}
elseif($findend == 7){
return '#DF3D82';
}
elseif($findend == 8){
return '#A8CD1B';
}
elseif($findend == 9){
return '#088DA5';
}
else{
return '#292421';
}
}
its a long code process i want to reduce that code and want it through loop and functions.
I want That for every Id whatever i will get from the database for that i want a random color. atleast color should not be repetaed before 30 id i am newbie here so please help me in this.
just store the last select color id to your db or some place hten get use following code it's simple
public function get_color($lastid){
$colors = ['#455C4F', '#CC5543', '#4A572C',.....];
return $colors[$lastid];
}
try this, it will gives you multi-color, you can handle it as you want.
<?php
foreach ($rowset as $key => $value)
{
$colorrange=str_split($value->id);
$findend=end($colorrange);
$response[$key]['color'] = $this->get_color();
}
/****Random*Color**Function***/
function get_color(){
mt_srand((double)microtime()*1000000);
$c = '';
while(strlen($c)<6){
$c .= sprintf("%02X", mt_rand(0, 255));
}
$color="#".$c;
return $color;
}
?>

PHP if/else differences between return and echo?

I am not understanding this ?quirk? of php at all... as I am looking over other peoples code I see that some people leave out the else statement completely and just place a "return false;" statement.
It seems this trick only works for the return statement and as you can see in the cases below it does not work when echoing text.
This is strange, take case two for example, surely this function is read proceeduraly, so the function will return "true" inside the if statement because the condition is met however when it leaves the if/else statement it should return FALSE because there is no ELSE statement. This DOES NOT happen and the function still returns true.
I can't make sense of this so hopefully someone can explain?
// Case 1
function checkNumber1($number) {
if ($number === 10) {
return true;
} else {
return false;
}
}
$number = 10;
var_dump(checkNumber1($number)); // Returns true
// Case 2
function checkNumber2($number) {
if ($number === 10) {
return true;
}
return false;
}
$number = 10;
echo '<br>';
var_dump(checkNumber2($number)); // Also returns true??
// Case 3
function checkNumber3($number) {
if ($number === 10) {
echo 'true' . '<br>';
} else {
echo 'false' . '<br>';
}
}
$number = 10;
echo '<br>';
checkNumber3($number); // Returns true
// Case 4
function checkNumber4($number) {
if ($number === 10) {
echo 'true' . '<br>';
}
echo 'false' . '<br>';
}
$number = 10;
checkNumber4($number); // Returns true and then false???
The return statement in a function immediately ends execution of the current function and returns control.

php function to return next/previous item in list

I have a PHP file that loads three different pages: a user's followers, following, and their friends (represented below by a, b, and c). Each "page" has different privacy settings depending on who's viewing the website, so a, b, and c have true/false values. If the value is false, then that user cannot view the page. I want to create next and previous buttons, but in order to determine which page is next/previous, I need to factor in the user's privacy. For example, if the user only shows b, there would be no next/previous, but if they showed a, and c, then next/previous for a would be c, and for c it would be a. I wrote some code below that tries to accomplish this, but is there a simpler way to do this without being so repetitious? It's also important that it loop, so even if I'm on page c, the next button will bring me to page a.
$a = $_GET['a']; // true/false
$b = $_GET['b']; // true/false
$c = $_GET['c']; // true/false
$cur = // current page: a, b, or c
if($cur = $a) {
if($b) {
$next = $b;
}
else if($c) {
$next = $c;
}
else {
$next = $a;
}
if($c) {
$previous = $c;
}
else if($b) {
$previous = $b;
}
else {
$previous = $a;
}
}
if($cur = $b) {
if($c) {
$next = $c;
}
else if($a) {
$next = $a;
}
else {
$next = $b;
}
if($a) {
$previous = $a;
}
else if($c) {
$previous = $c;
}
else {
$previous = $b;
}
}
if($cur = $c) {
if($a) {
$next = $a;
}
else if($b) {
$next = $b;
}
else {
$next = $c;
}
if($b) {
$previous = $b;
}
else if($a) {
$previous = $a;
}
else {
$previous = $c;
}
}
UNTESTED
$PRIVACY_PAGES[0] = "followers.php";
$PRIVACY_PAGES[1] = "following.php";
$PRIVACY_PAGES[2] = "friends.php";
function getNextPage($currPageName, $userPrivacy){
//$userPrivacy is array of boolean same order as $PRIVACY_PAGES
$currIdx = getPageIndex($currPageName);
$loopStart = 0;
if($currIdx > -1){
$loopStart = $currIdx+1;
}
if($currIdx == 2){//he is on last page
return "#";
}
for($v=$loopStart;$v<count($userPrivacy);$v++){
if($userPrivacy[$v]==true){
return $PRIVACY_PAGES[$v];
}
}//for loop
return "#";//he have no permission to view any page further.
}
function getPageIndex($currentPageName){
for($p=0;$p<count($PRIVACY_PAGES);p++){
if($PRIVACY_PAGES[0] == $currentPageName)
return $p;
}//for loop
return -1;//he is on another page, like index.php or gallery.php...
}
/////////////
//example :
$userPrivacy[0] = true;
$userPrivacy[1] = false;
$userPrivacy[2] = true;
$next = getNextPage("followers.php", $userPrivacy)
//$next should be friends.php
< html >
:
:
< a href="< ? php echo $next;?>">Next< /a >
an object orientated solution would be clean here, consider this pseudo code:
class page {
private $nextpage;
private $prevpage;
private $permission;
function __construct($nextpage, $permission)
{
$this->nextpage = $nextpage;
$this->permission = $permission;
}
public function GetNextPage($first = $this)
{
if ($this->nextpage == null || $first == $this) {
return false;
} elseif ($this->nextpage->isAllowed()) {
return $this->nextpage;
} else {
return $this->nextpage->GetNextPage($first);
}
}
public function isAllowed()
{
// Some authorization voodoo here
return $_SESSION['userpermissions'] == $permission;
}
}
Same code can be used for previous page. You could even make it dynamic in order to save you redundant code for next and previous.
Now all you have to do is inistantiate each page at the start of your application and you can easily browse through them.

Adding conditions dynamically in php if condtion

I am trying to add a condition dynamically in the if condition . But it is not working . Please help me to fix the issue.
I am trying a code like this
$day_difference = "some integer value";
if(sheduled_time == 'evening'){
$condition = '>';
}else{
$condition = '==';
}
then
if($day_difference.$condition. 0){
echo "something";
}else{
echo "h";
}
An alternative to gerald's solution; I would suggest that you use a function that validates the inputs using a switch-case operation:
function evaluate ($var1, $operator, $var2)
{
switch $operator
{
case: '<': return ($var1 < $var2);
case: '>': return ($var1 > $var2);
case: '==': return ($var1 == $var2);
}
return null;
}
What you need is the eval() method.
I.e.
$var1 = 11;
$var2 = 110;
$cond1 = '$var1 > $var2';
$cond2 = '$var1 < $var2';
if(eval("return $cond1;")){
echo $cond1;
}
if(eval("return $cond2;")){
echo $cond2;
}
As justly noted beneath, you should exercise the necessary precautions when using this method!
This is not the way to do this.
Just define a function which returns true if the desired conditions are met.
For example, we can define the function decide which receives two arguments, $day_difference and $scheduled_time:
function decide($day_difference, $scheduled_time)
{
if($scheduled_time == 'evening')
{
return $day_difference > 0;
}
else
{
return $day_difference == 0;
}
}
And use it like so:
if( decide($day_difference, $scheduled_time) )
{
echo "something";
}
else
{
echo "h";
}
according to your requirements this can be done using the PHP eval() function which i don't recommend using it only when necessary.
you can check When is eval evil in php?
you can use the below script instead:
if( $sheduled_time == 'evening' && $diff > 0 )
{
echo "This is the Evening and the Difference is Positive";
}
else if($diff == 0)
{
echo "This is not evening";
}
Thankyou for helping me solve my question
I solved this in another way
$day_difference = "some integer value";
$var1 = false ;
if($sheduled_time == 'evening_before'){
if($day_difference > 0 ){
$var1 = true ;
}
}else{
if($day_difference == 0 ){
$var1 = true ;
}
}
if($var1 === true){
echo "something";
}else{
echo "h";
}

Categories