PHP - Bitwise Operators
Hi every one,
I just want to know what is the use of '<<' and '>>' operators in php Similar TutorialsHere is a simple script which uses bitwise operations to determine whether or not a checkbox has been set. The problem is that if you use the $alpha array, the script doesn't produce the results you should expect. For example, if you set the last checkbox while using the $alpha array, all the checkboxes become set. I partially know why this happens as the PHP-Manual enlightened me: Quote From: http://www.php.net/manual/en/language.operators.bitwise.php Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. I attempted to use the GMP_* functions but because those aren't part of the PHP-Standard-Library, I do not wish to rely on them. Is there any way to make these functions work for integers beyond 2^31? Here is a standalone script I'm using to make these tests. $alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $delta = range('a', 'z'); function generate($array){ $n = count($array); $c = array(); for($i = 0; $i < $n; ++$i){ $c[bcpow(2, $i)] = $array[$i]; } return $c; } function set($array, $post){ $c = 0; foreach($array as $key => $val) if(isset($post['c'.$key])) $c |= $key; return $c; } function check($num, $category){ if($num & $category) return 'CHECKED'; return ''; } function checkboxes($array, $numval=0){ $i = 0; $form = ''; foreach($array as $key => $val){ $checked = check($numval, $key); $form .= '<input type="checkbox" '.$checked.' name="c'.$key.'" id="c'.$key.'">' . '<label for="c'.$key.'"> '.$val.'</label><br />'; ++$i; } return $form; } $array = generate($alpha); $num = 0; if(isset($_POST['action'])){ $num = set($array, $_POST); echo $num; } echo '<form action="y.php" method="post" style="width: 400px; border: 1px solid black;">'; echo checkboxes($array, $num); echo '<input type="submit" name="action" value="Set" />'; echo '</form>'; Hi all, Is it possible in php to read data from file as binary and operate on it with bitwise operators and save result as binary. Thanks So I have coded php for about 5-6 yrs and have never really needed to use binary conversions and the bitwise operator like >> or << . I took a php class in college but that basically consisted of the students trying to learn php on their own... So i have never had any exposure to that portion of php coding. I have to take an exam on PHP with a bunch of questions that DO NOT show how good of a coder you are. There are a bunch of questions on bitwise operators and binary conversions... Am I missing something??? Whats the point of converting a string to binary or knowing how to do this in your head? Any help? I'm at kind of a loss with this. I've read the docs for ~ bitwise NOT, and for ip2long() and I can't see why this is happening. On 2 machines with 32 bit OSs (one PPC Mac, and one Linux box), this does what I'd expect it to do. On an Intel Mac with a 64 bit version of OS X, it does not. echo abs(~ip2long('255.255.255.0')) + 1; I would expect this to return a value of 256. On a PowerMac, dual G5 OS X 10.5.8, (32 bit) and PHP 5.2.11 it returns 256 On a hosting server (unsure what processors) Linux OS (32 bit) and PHP 5.2.14, it returns 256 On an Intel Mac, Core2 Duo, OS X 10.6.8 (64 bit) and PHP 5.2.17, it returns 4294967042 Have I overlooked something in the manual that would explain this, or am I doing something fundamentally wrong with one of the functions? hi all, I have an array(1,2,3,4) and i make a form and make checkboxes for this array and user selects 2,3 and 4 when user submit form then i save it in table by making selected check boxes and converting selected values into bitwise equivalent value like this foreach($data['meal_types'] as $v){ $mealTypeBits += pow(2,$v-1); } Now when i have to show user his selected data how will i compare table bitwise saved record with array(1,2,3,4) to get the values that he checked while saving. I came across these pieces of code and have been trying to understand this operator -> Or if it is a operator. I have searched and couldn't find explanations. In trying to learn I need to know what is is used for. Is it used only with classes? $m->myMethod(); return $this->x; Hi guys! I am trying to understand why the final value of $m equals 40 in the following code Code: [Select] <?php $i = 29; $j = 11; $m = 10; $j = ($j - 4) / 2; $m += $j * 10; echo "m = ".$m."<br>"; //Equals 40 ?> Can anyone explain me please? I feel very confused right now. I have a query that is very messy. I have tried using () to seperate everything and when I do it just all goes wrong. here is the query SELECT posts.*, users.*, countries.countryID, countries.country FROM posts INNER JOIN users ON users.userID = posts.postUserID INNER JOIN countries ON countries.countryID = users.userCountry WHERE posts.cityID = '".$row_rs_city['cityID']."' AND posts.type = 'sightseeing' OR posts.cityID = '".$row_rs_city['cityID']."' AND posts.type = 'Inner city sightseeing' OR posts.cityID = '".$row_rs_city['cityID']."' AND posts.type = 'Outer city sightseeing' ORDER BY posts.postID DESC Is there a way of re-writing this so that it has brackets seperating everything and it will still work. It works for the minute but re- writing posts.cityID = '".$row_rs_city['cityID']."' inbetween every OR just seems wrong. Thanks for your help guys I'm trying to get an equation from a user that types it in the url, ex) 1+2+3. I can get the 1,2,3 fine, but the + operator is no longer in the string. Same with the * and / operators. Is there a way to keep them as a string using $_GET?
i'm trying to develop a deeper understanding of sessions, and I found this article on php.net regarding sessions with the following script;
<?php // Get the private context session_name('Private'); session_start(); $private_id = session_id(); $b = $_SESSION['pr_key']; session_write_close(); // Get the global context session_name('Global'); session_id('TEST'); session_start(); $a = $_SESSION['key']; session_write_close(); // Work & modify the global & private context (be ware of changing the global context!) ?> <html> <body> <h1>Test 2: Global Count is: <?=++$a?></h1> <h1>Test 2: Your Count is: <?=++$b?></h1> <h1>Private ID is <?=$private_id?></h1> <h1>Gloabl ID is <?=session_id()?></h1> <pre> <?php print_r($_SESSION); ?> </pre> </body> </html> <?php // Store it back session_name('Private'); session_id($private_id); session_start(); $_SESSION['pr_key'] = $b; session_write_close(); session_name('Global'); session_id('TEST'); session_start(); $_SESSION['key']=$a; session_write_close(); ?> [EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (lveillette AT silexmultimedia DOT com) on 19-NOV-09.]I do not understand line 21 and 22. <h1>Test 2: Global Count is:<?=++$a?></h1>If I change this to; <h1>Test 2: Global Count is:<?php echo =++$a; ?></h1> or <h1>Test 2: Global Count is:<?php =++$a ?></h1>I would get a parse error, unexpected "=" in line 21. Can anyone explain why this is? * Why is it being echoed * Why can I not use echo in this case * Why does the code not start with <?php ? * What does line 21 even mean? =++$a? Thanks in advance guys! Edited by empec, 13 July 2014 - 11:30 AM. In php is there a way to shortcut logical operators... example: Code: [Select] if ($row['CustomerSaas'] == 'Yes' && ($row['CustomerSaasPaidStatus'] == 'Trial' || $row['CustomerSaasPaidStatus'] == 'Trial Ended')) { to Code: [Select] if ($row['CustomerSaas'] == 'Yes' && ($row['CustomerSaasPaidStatus'] == 'Trial' || 'Trial Ended')) { hi everyone
i keep seeing the following Comparison Operators:
<>i see it used in the following context: if ($connection <> 'SSL') { $connection = 'NONSSL'; }be grateful if somone would tell me what it means, i looked online but could not find the symbol thanks While going through an instructional book, I ran across some code that I didn't immediately understand. I've stripped it down to the relevant bits: function example($object_a, $object_b) { $compare = $object_a->id == $object_b->id; return another_function('argument 1') && $compare || another_function('argument 2'); } My first confusion was this line: $compare = $object_a->id == $object_b->id; Does this set $compare to TRUE if the ids match and FALSE if they do not? And the second confusion: return another_function('argument 1') && $compare || another_function('argument 2'); What is returned if the ids match? What is returned if they are different? When I try testing this out on my machine, it returns both functions whether or not the ids match, but I know that's not what's supposed to happen. Can anyone break this down for me? Thanks. Hello I'm trying to use PHP "for loops" to build a table of 10 rows with 5 columns and I'm sure there's a better way to do this, but the result is the page won't fully load and continually spins its wheel. Here's the code: Code: [Select] $states = array(1 => 'AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','OZ','PA','PR','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI' ); <table id="stateCheck"> <?php for ($i = 1; $i <= 10; $i++) { echo '<tr>'; for ($j = 5*$i; $j <= $j+4; $j++) { echo '<td> <input type="checkbox" name="state" value="'.$states[$j].'" /> '.$states[$j].' </td>'; } echo '</tr>'; } ?> <tr> <td> <input type="checkbox" name="state" value="WV" /> WV </td> <td> <input type="checkbox" name="state" value="WY" /> WY </td> </tr> </table> Is it breaking because I'm using arithmetic operators to define the nested for loop? Many thanks Hello. Im having trouble using a Tempory Operator in a list. maybe someone might know a way around it. so the list below has 3 Tempory Operators. the first 1 looks for pages with links that are internal links the first 2 looks for pages with links that are external links the first 3 looks for pages with links that have no links if the link is a "nonTitle" it will be a normal list item if the link is a "title" it will be a header for a sub list (class="subexpandable") the problem is that every time it gets to the '; at the end of each Tempory Operators it breaks THIS IS NOT WORKING Code: [Select] <ul> //FIND INTERNAL LINKS echo $type == "internal" && $list == "nonTitle" ? '<li><a href="index.php">'.$title.'</a></li>' : '<li><a href="index.php" class="subexpandable">'.$title.'</a>'; //FIND EXTERNAL LINKS echo $type == "external" && $list == "nonTitle" ? '<li><a href="http://www.url.com">'.$title.'</a></li>' : '<li><a href="http://www.url.com" class="subexpandable">'.$title.'</a>'; //FIND NON LINKS echo $type == "non" && $list == "nonTitle" ? '<li><a>'.$title.'</a></li>' : '<li><a class="subexpandable">'.$title.'</a>'; //GET SUB LINKS echo' <ul class="subcategoryitems" style="margin-left: 15px"> <li><a href="">sub link</a></li> </ul> </li> </ul>'; If i put the sub level inside of each type it works but then i keep having to use the same code over. THIS IS WORKING Code: [Select] <ul> //FIND INTERNAL LINKS echo $type == "internal" && $list == "nonTitle" ? '<li><a href="index.php">'.$title.'</a></li>' : '<li><a href="index.php" class="subexpandable">'.$title.'</a> <ul class="subcategoryitems" style="margin-left: 15px"> <li><a href="">sub link</a></li> </ul> </li>'; //FIND EXTERNAL LINKS echo $type == "external" && $list == "nonTitle" ? '<li><a href="http://www.url.com">'.$title.'</a></li>' : '<li><a href="http://www.url.com" class="subexpandable">'.$title.'</a> <ul class="subcategoryitems" style="margin-left: 15px"> <li><a href="">sub link</a></li> </ul> </li>'; //FIND NON LINKS echo $type == "non" && $list == "nonTitle" ? '<li><a>'.$title.'</a></li>' : '<li><a class="subexpandable">'.$title.'</a> <ul class="subcategoryitems" style="margin-left: 15px"> <li><a href="">sub link</a></li> </ul> </li>'; </ul>'; so is there a way to do the first example without having to do the second example thanks ricky I was looking at the manual:
http://php.net/manua....precedence.php
And I notice that the parenthesis () operator and print operator are missing from the list. Why so? I would like to know where these operators fall in the precedence and associativity chart.
Can someone help me understand parentheses structure? Why here does the second empty() have no parentheses before it and an extra parentheses at the end? if (empty($subject) && empty($text)) { .... And here, why is there an extra parentheses at the end? if (empty($subject) && (!empty($text))) { ... And here, why double parentheses in the 1st empty() and none before the 2nd empty() ? if ((!empty($subject)) && empty($text)) { ... Thank You! michael I'm using the following code. I have tried placing parenthesis around $date1 and $date2 to separate them. No matter where I place the parenthesis Dreamweaver keeps giving me a syntax error. If I remove the second operator $date2 with the && the error goes. checked all my books but I can't see what is probably a stupid error ! Code: [Select] if ($row_sales_shipping_tax['cdate'] >= $date1 && <=$date2 ) Thanks for the help ! 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 Ok here's my issue, im trying to create a program that will calculate the total cost of an item, tax, shipping and shipping date, so far i've ran into a problem setting up my "If" statement with the perameters needed to calculate the shipping cost, Here's the code i have so far: <?php $Cost = $_POST['fielda']; $Tax = ($Cost * .06); $Sub = ($Cost + $Tax); $Ship = $Total = ($Cost + $Tax + $Ship); if ( $Sub <= 25.99 ){ print "$Ship: 3.00<br>"; } elseif ($Sub >= 26.00 || <= 50.99 ){ print "$Ship: 4.00<br>";} elseif ($Sub >= 51.00 || <= 75.00) { print "$Ship: 5.00<br>";} elseif ($Sub > 75.00) { print "Ship: 6.00<br>";} else { print ("Cost : $Cost<br> Tax: $Tax<br> Shippingtotal is $$Total");} ?> Here's the error i keep getting: Parse error: syntax error, unexpected T_IS_SMALLER_OR_EQUAL in C:\wamp\ on line 16 any help i can get will be greatly appreciated, I also need to know how to do the shipping date (15 days) as well if you can help with that as well |