PHP - Prefix Decrementing Operator Vs. Postfix Decrementing Operator
I'm having trouble understanding the behavior of Prefix decrementing operator VS. Postfix decrementing Operator
Postfix decrementing Operator Code: [Select] <?php $a = 1; $a = --$a + 1; echo $a; // this outputs 1 ?> VS.... Prefix decrementing operator Code: [Select] <?php $a = 1; $a = $a-- + 1; echo $a; // this outputs 2 ?> Similar TutorialsHi guys, I have written this code, it might look messy but I am learning so I don't really mind that but my main concern is that it is not working, could anyone help me out? I am using an array to "unsubscribe" from multiple events at once, now I also need to decrement the amount of participants in that event, the code is working I am able to unsubscribe from events but the currentparticipants field is not updating.. any idea why? This is the code that runs when you click unsubscribe : Code: [Select] if(isset($_POST['eventsID']) && count($_POST['eventsID'])) { $eventsID = $_POST['eventsID']; //Ensure values are ints $deleteIDs = implode(', ', array_map('intval', $_POST['eventsID'])); $query = "DELETE FROM Eventparticipants WHERE eventsID IN ({$deleteIDs})"; //Debug line echo ''; mysql_query($query) or die(mysql_error()); $result5=mysql_query("SELECT maxparticipants, currentparticipants FROM Events WHERE eventsID='$eventsID'"); $row5=mysql_fetch_assoc($result5); $currentparticipants = $row5['currentparticipants']; $maxparticipants = $row5['maxparticipants']; $newcurrentparticipants = $currentparticipants--; $sql="UPDATE Events SET currentparticipants='$newcurrentparticipants' WHERE eventsID='$eventsID'"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } } And here is the code where you actually click unsubscribe Code: [Select] $result2 = mysql_query("SELECT * FROM Eventparticipants WHERE participant = '$username'") or die(mysql_error()); echo '</br><b>You are currently taking place in these events: </b></br>'; echo "<form action='' method='POST' onsubmit='return executeOnSubmit();'>"; echo '<table border="0">'; while($row2 = mysql_fetch_array($result2)) { echo '<tr>'; echo '<td><a href="showevent.php?eventsID='; echo $row2['eventsID']; echo '">'; echo $row2['eventdescriptionheader']; echo '</a></td>'; echo "<td><input type='checkbox' name='eventsID[]' value='{$row2['eventsID']}' /></td>"; echo '</tr>'; } echo '</table>'; echo "</br><input type='submit' value='Unsubscribe to event(s)' name='delete' />"; echo '</form>'; And here is the full script in one Code: [Select] <?php include 'connect.php'; include_once "markdown.php"; session_start(); if(!isset($_SESSION['username'])) { echo 'You have to be a registered member to be able to view your space.<br><br> <a href="register.html">Click here to register</a>'; echo '<br><br><br><br>Or if you are already a member, please login to use this area.<br>'; echo ' <form method="POST" action="loginverification.php"> <table border="0"> <tr><td> Username: </td><td><input type="text" name="username" size="15" /></td></tr> <tr><td>Password:</td><td> <input type="password" name="password" size="15" /></td></tr> </table> <div align="center"> <p><input type="submit" value="Login" /></p> </div> </form>'; } else{ if(isset($_POST['eventsID']) && count($_POST['eventsID'])) { $eventsID = $_POST['eventsID']; //Ensure values are ints $deleteIDs = implode(', ', array_map('intval', $_POST['eventsID'])); $query = "DELETE FROM Eventparticipants WHERE eventsID IN ({$deleteIDs})"; //Debug line echo ''; mysql_query($query) or die(mysql_error()); $result5=mysql_query("SELECT maxparticipants, currentparticipants FROM Events WHERE eventsID='$eventsID'"); $row5=mysql_fetch_assoc($result5); $currentparticipants = $row5['currentparticipants']; $maxparticipants = $row5['maxparticipants']; $newcurrentparticipants = $currentparticipants--; $sql="UPDATE Events SET currentparticipants='$newcurrentparticipants' WHERE eventsID='$eventsID'"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } } $username = $_SESSION['username']; $result = mysql_query("SELECT * FROM Members WHERE username = '$username'") or die(mysql_error()); while($row = mysql_fetch_array($result)) { echo '<b>' . $username . '</b></br></br>'; echo '<img src="data:image/jpg/png/jpeg;base64,' . base64_encode( $row['image'] ) . '" height="150" />'; echo '</br>'; $selfdescription = Markdown($row['selfdescription']); echo $selfdescription; echo '</br></br>'; echo '<table border="0">'; echo '<tr>'; echo '<td>'; echo 'Email: '; echo '</td>'; echo '<td><b>'; echo $row['email'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Date joined: '; echo '</td>'; echo '<td><b>'; print date('d M Y', strtotime($row['datejoined'])); echo "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Last visit: '; echo '</td>'; echo '<td><b>'; print date('d M Y', strtotime($row['lastvisit'])); echo "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'First name: '; echo '</td>'; echo '<td><b>'; echo $row['firstname'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Family name: '; echo '</td>'; echo '<td><b>'; echo $row['familyname'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Date of birth: '; echo '</td>'; echo '<td><b>'; print date('d M Y', strtotime($row['dob'])); echo "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Gender: '; echo '</td>'; echo '<td><b>'; echo $row['gender'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'County: '; echo '</td>'; echo '<td><b>'; echo $row['county'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo 'Postcode: '; echo '</td>'; echo '<td><b>'; echo $row['postcode'] . "</b>"; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>'; echo '</br>'; echo '<form action="editprofile.php">'; echo '<input type="submit" name="" value="Edit Profile">'; echo '</form>'; echo '</td>'; echo '</tr>'; echo '</table>'; } $result2 = mysql_query("SELECT * FROM Eventparticipants WHERE participant = '$username'") or die(mysql_error()); echo '</br><b>You are currently taking place in these events: </b></br>'; echo "<form action='' method='POST' onsubmit='return executeOnSubmit();'>"; echo '<table border="0">'; while($row2 = mysql_fetch_array($result2)) { echo '<tr>'; echo '<td><a href="showevent.php?eventsID='; echo $row2['eventsID']; echo '">'; echo $row2['eventdescriptionheader']; echo '</a></td>'; echo "<td><input type='checkbox' name='eventsID[]' value='{$row2['eventsID']}' /></td>"; echo '</tr>'; } echo '</table>'; echo "</br><input type='submit' value='Unsubscribe to event(s)' name='delete' />"; echo '</form>'; $result4 = mysql_query("SELECT * FROM Events WHERE hoster = '$username'") or die(mysql_error()); echo '</br><b>You are currently hosting these events: </b></br>'; echo "<form action='' method='POST'>"; echo '<table border="0">'; while($row4 = mysql_fetch_array($result4)) { echo '<tr>'; echo '<td><a href="showevent.php?eventsID='; echo $row4['eventsID']; echo '">'; echo $row4['eventdescriptionheader']; echo '</a></td>'; echo '</tr>'; } echo '</table>'; echo '</form>'; } ?> Much appreciated! Hi, This ones stumped me a little as i've done this previously and it seemed to work fine: I have a form to add with two password boxes, the IDs are different as they should be but the type is the same: Code: [Select] <form action="<?php echo $PHP_SELF;?>" method="post"> <p>New Password: <input type="password" id="newpassword" name="newpassword" /></p><br /> <p>Confirm Password: <input type="password" id="confirmpassword" name="confirmpassword" /></p><br /> <p><input type="submit" name="submit" value="submit"></p> </form> I have this code to check if they are both equal then md5 them and add them to the database: Code: [Select] // Check if button name "submit" is active, do this if(isset($_POST['submit'])) { //variable to identify user $email = ($_SESSION['email']); //post variable from form $newpassword = $_POST['newpassword']; $password = $_POST['confirmpassword']; //if passwords are not equal if($password != $confirmpassword) { echo "The passwords do not match<br />"; //debugging - to see if they are equal or not - remove afterwards echo $password . "<br />"; echo $newpassword . "<br />"; } //if passwords are equal if($newpassword == $password) { //use md5 so they match when logging in $password = md5($password); $newpassword = md5($newpassword); $sql= "UPDATE users SET password='$newpassword' WHERE username='$email'"; $result = mysql_query($sql); if($result) { echo "Congratulations You have successfully changed your password"; } } } I've tried to explain my thinking as best i can in the code, the debugging part at the top shows that both values seem to be identical yet i'm being thrown into the not equal loop and they aren't adding to the database. Can anyone explain what i'm doing wrong here? I imagine its only minor but its thrown me. Cheers Hi Ok, so I pick a random value 23 for example and I want this value to be in between two other values. E.g. if 23 is in between 20 and 30, then continue otherwise die. How can I do this? I've been looking through the Joomla docs trying to understand how everything works and I've seen something that I don't understand and cannot find an answer to anywhere on the net. The basic question is what is the ampersand used for in this conditional he if (!($mask & 1) && is_string($var)) { The two in the middle are obviously the AND part of the conditional. I know it can be used for creating references to variables but I don't think this is what is happening here. I've seen people using it to test for odd and even numbers too but with no explanation of how it works/what it does. The full code is below: function _cleanVar($var, $mask = 0, $type=null) { // Static input filters for specific settings static $noHtmlFilter = null; static $safeHtmlFilter = null; // If the no trim flag is not set, trim the variable if (!($mask & 1) && is_string($var)) { $var = trim($var); } // Now we handle input filtering if ($mask & 2) { // If the allow raw flag is set, do not modify the variable $var = $var; } elseif ($mask & 4) { // If the allow html flag is set, apply a safe html filter to the variable if (is_null($safeHtmlFilter)) { $safeHtmlFilter = & JFilterInput::getInstance(null, null, 1, 1); } $var = $safeHtmlFilter->clean($var, $type); } else { // Since no allow flags were set, we will apply the most strict filter to the variable if (is_null($noHtmlFilter)) { $noHtmlFilter = & JFilterInput::getInstance(/* $tags, $attr, $tag_method, $attr_method, $xss_auto */); } $var = $noHtmlFilter->clean($var, $type); } return $var; } This might is a newbie/stupid question. But, what does this operator below means? -> Hi I'm trying to work why the following paramter doesnt work properly. it seems to be ignoring the 'and' part of the query i am using a mysql 5.1.41 server $stmt = $mysqli ->prepare("select CandidateVotes,CandidateTitle, CandidatefirstName ,CandidateLastName,CandidateID from Candidate where ( CandidateFirstName like ? and CandidateLastName like ?) order by CandidateVotes DESC LIMIT 0,?"); $stmt->bind_param('sss', $code1,$code2,$noVotes); $code1="%".$searchFirstName."%"; $code2="%".$searchLastName."%"; $stmt->execute(); $stmt->bind_result($candidateVotes,$candidateTitle,$candidateFirstName,$candidateLastName,$candidateID); I see a couple people using the ? operator in php and was curious as to how it works? $a === $b if $a is equal to $b, and of the same type when would you ever need to use this operator? I mean if its not == then its going to be false so why even test if its the same type. and if it is == then in theory it has to be the same type so why test it? Am i completely over looking something? I'm trying to use the executor operator to print a list of all files in my home directory onto the browser. I am using Ubuntu 12.04 and therefore I am using standard unix commands. Unfortunately, it doesn't print anything to the browser. But I don't even understand how this is supposed to work. Which user in /etc/passwd is the actual commands running as? How does PHP know which system user to run the commands as?
$out = `cd ~ && ls -l`; echo '<pre>'.$out.'<pre>'; if($value != "0"){ $errors[] = 'Invalid option chosen'; }$value is a string. IF $value equals '00', it doesn't work why? It does not equal 0? I'm trying to check if a value equalis 1 or 0. LITERALLY the string has to be 1 or 0, if not I need to error out. Why is this so difficult? How does 2 zero's (00) = 0? Doesn't make sense. Especially when it's matching 2 STRINGs.. If it were a numeric value I could see PHP saying 00 might equal 0. But how does 00 and 0 equal the same thing? makes no sense. Edited by Monkuar, 23 January 2015 - 06:27 PM. I just started my journey into OOP, just looking for a simple explanation as to why the script echo's nothing. (last line) Code: (php) [Select] <?php class Dog { public $name; public function bark() { echo "{$this->name} says Woof!"; } } class Poodle extends Dog { public function bark() { echo "Yip"; } } $furball = new Poodle; $furball->name = "furball"; $furball->Dog::bark(); ?> This is the full error: Fatal error: [] operator not supported for strings in D:\Programs\AppServ\www\test\test.php on line 19 I have comented on the error line. function structure(){ $argNum = func_get_args(); $temp = $argNum; (int)$pointer = -1; $xmlStructure = array(); foreach ($temp as $key => $value) { if ($value == 'in') { if ($pointer == -1) { $pointer = 0; } else{ $pointer = $pointer + 1; } }elseif ($value == 'out') { $pointer = $pointer - 1; }; if($pointer != -1){ $xmlStructure[$pointer][] = $value; //THIS is the 19'th line. }else{ $xmlStructure[] = $value; } } return $xmlStructure; } function test_print($item2, $key) { echo "$key. $item2<br />\n"; } $a = structure('0','in','00','01','02'); array_walk($a,'test_print');
Is there a subtle difference between Thank you. hello i keep seeing Ternary Operators like this Code: [Select] $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; but how would i turn this if statement in to a Ternary Operator ? Code: [Select] if($a == $b){ echo 'hello'; }else{ //do nothing } thanks I'm trying to build a math game. But I'm having trouble trying to make a variable calculate that contains an operator. Example: $c1_op = "+"; $a1_num_user = $_POST['a1_num']; $e1_num_user = $_POST['e3_num']; $row_1 = $a1_num_user . $c1_op . $e1_num_user; echo "result: " . $row_1; If I now input a 10 and a 2 I will get echo'd out: result: 10+2 It's not calculating. When I don't use any quotation marks then I will get the error "unexpected ;". I need the operator inside a variable, it's the nature of the math game, any idea how I can make it work so it calculates? ok guys I've made a script that will allow me to move items and up and a list using weight. The page loads fine the first time, then when you click on the up or down arrow it swaps the weight values and wrights them to the data base. On the same page I have Code: [Select] $data = mysql_query("SELECT * FROM columnleft ORDER BY weight ASC") or die(mysql_error()); while($info = mysql_fetch_array($data)) { $id[] = $info[id]; $weight[] = $info[weight]; } This is allowing me to loop in the upper and lower weights to the current item. So they can be changed. However I get a Code: [Select] [17-Mar-2011 18:25:11] PHP Fatal error: [] operator not supported for strings in dir/page on line 80 Line 80 is the Code: [Select] $weight[] = $info[weight]; So my guess is that its writing the weight to the database and trying to get an array at the same time? So it errors out. So if I'm right is there a way to prioritize so it will finish writing then load the rest? Hey all, when job_title property is equal to null, I want this to happen: Welcome to the blog of John Merlino. If it is not null then: Welcome to the blog of John Merlino, a web designer. //where web designer refers to the value stored in job_title So I come up with this: Code: [Select] echo "Welcome to the blog of " . $blogger->first_name . ' ' . $blogger->last_name . (!is_null($blogger->job_title)) ? ', ' . $blogger->job_title . '.' : '.'; But when job_title is null, all the page renders is this: Code: [Select] , . That's right. Just a comma, then a space, and then a period. What am I missing here? Thanks for response. As title says, I'm getting this error: Fatal error: [] operator not supported for strings in C:\Users\Administrator\Desktop\xampp\htdocs\arpg\locations_modules\2dmap\generic_map.php on line 225 Line 225 is: $monsters[ ] = $r->fields[0]; And this is the whole section if it helps any. Code: [Select] $nbmonsters=0; if($sql != "") { $r=$db->Execute($sql); if($r !== false) while(!$r->EOF) { if(($r->fields[0]+0) == 0) { $r->MoveNext(); continue; } $p=mt_rand(0,100); if(($r->fields[2]+0) != 100 && $p < ($r->fields[2]+0)) { $r->MoveNext(); continue; } if($r->fields[1] != "") { $res=false; $code='if ('.$r->fields[1].') $res=true;'; eval($code); if($res == false) { $r->MoveNext(); continue; } } $monsters[ ] = $r->fields[0]; $nbmonsters++; $r->MoveNext(); } if($r !== false) $r->Close(); } I have a method where the operator condition started getting too long and was becoming difficult to understand and troubleshoot. private function validateCallbackRequest():self { if($this->params->xyz < 3 || isset($this->x->bla['hi']) || soOnAndSoOnAndSoOn) { throw new Exception('Invalid params'); } return $this; } I could break it into sections, but would rather not duplicate all the exception throwing. private function validateCallbackRequest():self { if($this->params->xyz < 3 || isset($this->x->bla['hi'])) { throw new Exception('Invalid params'); } if(soOnAndSoOnAndSoOn) { throw new Exception('Invalid params'); } return $this; } I could assign variables, but don't really care for this all that much. private function validateCallbackRequest():self { $initialStuff=$this->params->xyz < 3 || isset($this->x->bla['hi']); $otherStuff=soOnAndSoOnAndSoOn; if($initialStuff || $otherStuff) { throw new Exception('Invalid params'); } return $this; }
Any recommendations? |