PHP - How Would I Turn This If Statement In To A Ternary Operator ?
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 Similar TutorialsHey 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. 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 ?> In this statement... $firstName = (isset($_SESSION['memberFirstName']) ? $_SESSION['memberFirstName'] : ''); Can isset() be replaced with most other functions, e.g. empty(), is_numeric(), is_null(), etc?? Thanks, Debbie if($AClass->select_error || $BClass->ErrorFile){ include("/path/to/files/".($AClass->select_error ? 'no_selector' : 'error_file_missing').".php"); exit; } if($CClass->WriteError){ include("/path/to/files/FileWriteError.php"); exit; } Probably a simple one for you folks, but I can't for the life of me work out how to make the above into 1 line of ternarys. Cheers, Rw I have just discovered ternary conditionals and really like the time and space saving, they seem pretty simple and look neater than a bunch of if else statements crammed together. The thing I would like to know is what is the best or correct method of usng the following; $page = isset($_GET['page']) ? $_GET['page'] : '1'; or do I need the extra parentheses like below; $page = (isset($_GET['page'])) ? $_GET['page'] : '1'; I understand that if I used a second conditon I would need the extra parentheses e.g $page = (isset($_GET['page']) && is_numeric($_GET[page'])) ? $_GET['page'] : '1'; Thanks! Please bear with me in the following exercise. I'm fairly new to php (but not coding) and am trying to push my skills for the future, so I'm going beyond a problem for which I already have a solution to see if I understand the coding principles correctly. I am trying to understand just how far I can push the ternary operator shorthand. I know how to do simple tasks, but I'm wondering if I can perform more than one command in the same statement? I'm a little confused because I'd like to both set a session variable and do a page redirect and I have a feeling that the order of these operations matters, so all I've done here may be incorrect. I have a form on the front page of my site that includes a checkbox that is required in order to enter the site. The form action goes to a page where this is checked, a $_SESSION variable is set, and the page is redirected. I am also not sure if I need the session_write_close(); command, or if it is in the right place. In the full length version, it could be moved into the set of commands following the IF. Here is the full length code that I would like to translate into shorthand: Code: [Select] <?php session_start(); if (isset($_POST['ConsentCheckbox']) { $_SESSION['Consented'] = 'true'; header('Location: http://www.mySite/welcome'); } else { header('Location: http://www.mySite/errors/NotConsented'); } session_write_close(); ?> The if/else conditions translate easily into these two lines of code, which could be one line if I didn't also need to set the session variable: Code: [Select] <?php session_start(); $_SESSION['Consented'] = isset($_POST['ConsentCheckbox']) ? 'true' : 'false'; header('Location: http://mySite.com/'.($_SESSION['Consented'] ? 'welcome' : 'error/NotConsented')); session_write_close(); ?> But, I really only need to set the $_SESSION variable if the $_POST['ConsentCheckbox'] is set. This makes the test on the following pages of my site much simpler (where I test to see if the $_SESSION variable is set and then either redirect to the consent form or load the desired page). SO, I'm wondering if it can be further condensed. I've come up with these possibilities, but am not totally sure. This has now become a theoretical exercise in coding for me. Here is what I think is possible, but I have a couple of outstanding questions, so I'd like some input, please. I first translated it into the following. I think this is correct, although I'm not sure if I need brackets around the multiple commands in the TRUE section. Code: [Select] <?php session_start(); isset($_POST['ConsentCheckbox']) ? $_SESSION['Consented']='true'; header('Location: http://www.mySite.com/welcome') : header('Location: http://www.mySite/errors/NotConsented'); session_write_close(); ?> Then, I wondered if I can even further condense it in the following way? Here is where the order of the commands is likely to break the code - and I'm not entirely sure that my use of double quotes will suffice instead of escaping out the end bracket of the header() command: Code: [Select] <?php session_start(); header('Location: http://www.mySite.com/'.(isset($_Post['ConsentCheckbox']) ? "welcome')"; $_SESSION['Consented'] = 'true' : "errors/NotConsented')"); session_write_close(); ?> Have I gone too far? Thanks 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? -> I see a couple people using the ? operator in php and was curious as to how it works? 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); $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>'; 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'); 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(); ?> 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.
Is there a subtle difference between Thank you. 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? |