Jump to content

[SOLVED] using ternary operators...


mkosmosports

Recommended Posts

Hello,

 

Is there a more elegant way to write the following piece of code, maybe using ternary operators?

IF isset($_GET['dir'])
{
IF ($_GET['dir'] == 'DESC' || $_GET['dir'] == 'ASC')
	$dir = $_GET['dir']	
}

 

Or is that the only and most effective way to do it?

 

Thanks for any suggestions!

 

 

Link to comment
Share on other sites

  $dir = isset($_GET['dir']) && in_array( strtolower( $_GET['dir'] ), Array( 'desc', 'asc' ) )
                              ? $_GET['dir'] : "some_default_value";

 

They each accomplish the same thing, so they're each just as effective.  One is slightly easier to read while the other uses less lines of code.  It's up to you to determine which to use.  :D

Link to comment
Share on other sites

fyi the in_array() function is quite an elobrate function for this case, especially if the matching is only 2.  In general you shouldn't be array matching if your pool is less than 5 items. 

 

just say

 

<?php
if(isset($_GET['dir']) && $_GET['dir'] == "DESC" || $_GET['dir'] == "ASC"){
$dir = $_GET['dir'];
}
?>

Link to comment
Share on other sites

Eh, I'd say until you can trace it down as causing a huge impact on performance it's fine.  It allows for any case-combination of 'desc' or 'asc', which if they're being inserted into a query is perfectly legal.

 

I suppose you could get sort of ugly and do this:

<?php
if(isset($_GET['dir']) && ($tmp = strtolower($_GET['dir'])) == "desc" || $tmp == "asc"){
  $dir = $_GET['dir'];
}
?>

Link to comment
Share on other sites

thats the power of php, there is not only 1 solution, in fact there are a million solutions to 1 problem, the trick is finding the most efficient one that makes the most sense to you.  As long as you don't write something that is so ugly that 95% of the php world would laught at you for it.

Link to comment
Share on other sites

I agree it works, but your invoking a function that needs not be invoking.

 

cause when you do an in_array it is really doing a

$count = count($array)

$i =0;

$match =0;

while($i<$count || $match ===0){

if($item == $array[$i]);

$match =1;

$i++;

}

 

vs a simple boolean test of a yes no.  I mean yes the performance is insignificant, but image a page where you had about a thousand test  of if it is this or that, and you use in_array for each.  That will add up.  I guess its the principle of the thing to me.  A you are creating a variable that needs not to be created.  B you are invoking additional steps to find the same solution, C it just looks more ugly to me :)

Link to comment
Share on other sites

True cooldude,

 

In the end, I will go with simply:

 

IF (isset($_GET['dir']) && ($_GET['dir'] == 'desc' || $_GET['dir'] == 'desc'))
$dir = $_GET['dir']	

 

but it looks like I may be able to use ternary operators to optimize code in many other instances of my script. I just started looking into them yesterday and I see a lot of potential.

 

On a side note, what do all you guys use when designing code and writing pseudocode? Is there a preferred piece of software. Im using Word, just wondering if there is a more appropriate alternative?

 

Thanks.

Link to comment
Share on other sites

$count = count($array)
$i =0;
$match =0;
while($i<$count || $match ===0){
if($item == $array[$i]);
$match =1;
$i++;
}

I highly doubt that's the code that in_array() invokes.  I'd wager that internally arrays are stored as hashes or binary search trees, or a combination of both.  In any case, using an array does add more overhead, I won't argue that.

 

A you are creating a variable that needs not to be created.

The array is created long enough to be passed to a function but not stored in any permanent variable, thus it is thrown away after passed to the function.  This is no different than the PHP interpretor allocating space in a symbol table for each of the strings "ASC" and "DESC".

 

:D

Link to comment
Share on other sites

IF (isset($_GET['dir']) && ($_GET['dir'] == 'desc' || $_GET['dir'] == 'desc'))
$dir = $_GET['dir']

 

Place curly brackets around your if statements, always; just trust me on that one.  Also, you are testing against 'desc' twice, what happened to 'asc'?

 

On a side note, what do all you guys use when designing code and writing pseudocode? Is there a preferred piece of software. Im using Word, just wondering if there is a more appropriate alternative?

Pen and scratch paper mostly or a white board and digital camera.

Link to comment
Share on other sites

I guess its just a design preference in the end, php is never meant to be so sophisticated that a single design structure idea as simple as this can make a dramatic impact on the performance.

 

Any way the way I design for the most part is I have a remote test serevr and I use notepad++, as its free, does pretty print and tabs in a manner I like.  Then I just ftp up the files from local to the server and test.  I don't write pseudo code, I just comment as I go and really just as a first run through try and accomplish the desired function I need, then after that is completed I look back at the code and look for adjustments to improve speed, such as reducing the number of queries, or the data that is queried, and so forth.

 

Back to the in_array();  Yes the variable is only a temporary thing as you don't define it, but just make a psedo one in the in_array() function, but the fact still remains that the data of the nodes in it are associated vs have 2 individual strings.  I guess it is like the classic argument of Print vs Echo.  (I believe echo is faster)

 

Some people like swiss cheese, some like provoloian, in the end everyone is a winner cause they got the cheese they want (wow what a horrible comparison, guess that is why I ain't a English major (ain't an english major that is classic))

Link to comment
Share on other sites

Yes, sorry, the double desc thing is a typo.

 

IF (isset($_GET['dir']) && ($_GET['dir'] == 'desc' || $_GET['dir'] == 'asc'))
{
$dir = $_GET['dir']
}

 

About the curly brackets. Youre really burstin my bubble on this one  :D I always thought and have been avoiding them if the if statement only contains one line. I do trust you, since you definitely seem like a more skilled php programmer than me, but do you have a brief explanation of why? Is it performance or organization related?

 

Thanks roopurt18

Link to comment
Share on other sites

there is a proto type using a ? for a single statement if, however it isn't readily used.  you are correct you do not need the { } on a single line statement, however it is always more logical to read them with the { } and leaves you open to add options to it later on.  I like to write my ifs as

<?php
if(This is True) {
//Do this
}
?>

with the opener spaced off the close of the if and everything indented one tab and the closer on the same line.

Link to comment
Share on other sites

Thanks cooldude,

 

The ? prototype would mean using ternary operators, no?

 

About the curly brackets in single-line if statements, I thought they would slow things down a little, since 2 additional lines need to be parsed. This is most likely wrong though, so, I guess Im a make a habit of always including the curly brackets then.

 

Thanks.

Link to comment
Share on other sites

I doubt there's any performance to be gained from including them as the PHP interpreter has to parse extra characters; however the parser is incredibly fast so you should not concern yourself with this.

 

The reason you include them is in case you add a statement to the body of the if later.  What if you are debugging the page and want to quickly add a logging function to confirm the test is passed, but you forget to add the curly brackets then:

 

// #1
if(isset($_GET['dir']) && ($_GET['dir'] == 'desc' || $_GET['dir'] == 'asc'))
  Logging::write("dir is set: {$_GET['dir']}");
  $dir = $_GET['dir']

// #2
if(isset($_GET['dir']) && ($_GET['dir'] == 'desc' || $_GET['dir'] == 'asc'))
  $dir = $_GET['dir']
  Logging::write("dir is set: {$_GET['dir']}");

 

In #1, the log will only be updated if the test is passed, but the $dir variable will always be set.  This may or may not cause effects on the page that affect your ability to debug it.

 

In #2, the log will always be updated which can confuse your debugging.

 

Each of those cases only affect your ability to debug the script, which isn't a huge deal because eventually you'll notice.  But what if you had put actual script code that affected the outcome of the script?  It could take you a long time to figure that one out.

 

Every book I've read on programming and every professor that I admired for their ability and knowledge always said the same thing:  Use curly brackets, even when they're optional.

 

I had many class mates who would only use them when necessary and they also tended to be the people that could never turn in a working program.  Programming is a methodical process; be consistent in your style and it will pay off with time saved later.

 

As a last note, I once fixed a very annoying bug when working as a contract programmer for a game development company.  We were developing a casino game in C++ for windows and occasionally the damn thing would crash.  None of us could figure out why.  Well, one day on pure, random chance, I saw this in the code:

  for(int i = 0; i < len; i++)
    SAFE_DELETE(list[i]);

What that code was intended to do was loop over a list of dynamically allocated objects and delete the memory associated with each of them.  SAFE_DELETE was a macro defined as:

#define SAFE_DELETE(x) delete (x); (x) = null;

In C / C++, a macro is directly substituted into the code, so the actual loop became this:

  for(int i = 0; i < len; i++)
    delete list[i]; list[i] = null;

Since the curly brackets are absent, the code is interpreted as:

  for(int i = 0; i < len; i++){
    delete list[i];
  }
list[i] = null;

What this does is for list[0] to list[max - 1] delete the item, which is correct; but it doesn't set them to null.  This means elsewhere the code could still attempt to use memory at list[0], list[1], list[2], etc. that was no longer allocated for the program.  Finally, after the loop ends, i is equal to the size of the list, so list[ i ] = null is actually trying to set a value that is beyond the end of the array; normally such an action would crash the program immediately and you'd catch it very quickly.  However, for some reason or other, setting an array index beyond the bounds of the array never caused the program to crash so it was only my chance encounter with that code that caused the bug to be fixed.

 

Once I fixed it, we all noticed that the program "mysteriously" crashed less.

 

Lastly, some people like to place the curly brackets on a line all by themselves; I find this to be a waste of a perfectly good line and place them right after the closing paren of the expression, like cooldude demonstrated.

Link to comment
Share on other sites

Thanks for this detailed response roopurt18.

 

Im gonna pick up these two habits then:

 

1. Always use curly brackets. (Thats a darn good example as to why to use them BTW. That one should be documented. ;D)

2. Use them like cooldude demonstrated (open after the closing paren on the same line as the statement)

 

Thanks again!

Link to comment
Share on other sites

Any way mark this solved, but in general develop some uniform coding structures with lots of commenting so that  when you make a logical error (not a syntax error) you can quickly find where it is.  If you can't debug your errors, or if someone else can't understand your flow, then you are in a load of trouble if you make a mistake.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.