Left right function in php

Implementing logical right shifting in PHP

PHP’s bitwise operators > implement Arithmetic Bit Shifting. This means:

  • Left shift (using
  • Right shift (using >> operator) discards bit(s) shifted off the right end of the bitfield and copy(ies) of sign bit are shifted in on the left end.

Logical Bit Shifting is different in that on right shifts, zeros are shifted in on the left end of the bitfield, affecting the sign of negative integer.

On 32 bit platforms, -2147483648 is the largest negative integer. Binary representation of this integer gives only the Most Significant Bit ON and all other bits are OFF . Shifting bits of this number $n steps to the right would actually shift in $n copies of the Most Significant Bit (or Sign Bit) and discard the same number of bits from the right.

$n = 30 echo decbin( -2147483648 ); // 10000000000000000000000000000000 //Arithmetic Right Shift echo decbin( -2147483648 >> $n ); // 11111111111111111111111111111110

The same is stated by PHP manual:

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved – PHP manual

Why Logical Right Shifting in PHP?

In php, bitwise operators are commonly used for manipulating colors, working with user permission management, character encoding/decoding etc and logical right shift is sometimes much needed to simplify operations. Many recommend its addition to php’s core and someone has even put up a request for comment for a new operator. No new operator is needed for Logical Left Shifts because logical and arithmetic left shift are the same.

Implementing logical right sift in PHP:

function logical_right_shift( $int , $shft ) < return ( $int >> $shft ) //Arithmetic right shift & ( PHP_INT_MAX >> ( $shft - 1 ) ); //Deleting unnecessary bits >

This function does not validate input. You have to make sure that both of the arguments $int and $shft are integer. Inappropriate arguments may cause unexpected results.

Tests

I have tested logical_right_shift on 32 bit platform, specially with key cases:

  • 0 where all 32 bits are OFF ;
  • ~ 0 or -1 where all 32 bits are ON ;
  • PHP_INT_MAX – a positive integer with 31 bits ON and just the sign bit OFF , and;
  • ~ PHP_INT_MAX – a negative integer (sign bit ON ) with 31 bits OFF .
//Tested With $int = 0 ; //0, -1, PHP_INT_MAX, ~PHP_INT_MAX $shift = 5; echo 'INT: '.$int ."\n"; echo 'Before: '.substr(str_repeat('0',32).decbin($int),-32)."\n"; echo 'After: '.substr(str_repeat('0',32).decbin(logical_right_shift($int,$shift)),-32); //INT: 0 //Before: 00000000000000000000000000000000 //After: 00000000000000000000000000000000 //INT: -1 //Before: 11111111111111111111111111111111 //After: 00000111111111111111111111111111 //INT: 2147483647 //PHP_INT_MAX //Before: 01111111111111111111111111111111 //After: 00000011111111111111111111111111 //INT: -2147483648 //~ PHP_INT_MAX //Before: 10000000000000000000000000000000 //After: 00000100000000000000000000000000

Notes

  • logical_right_shift() was tested to work fine with integers on 32 and 64 bit platforms. It should also work with strings (not tested).
  • Bitwise operators are high performance operators, often faster than arithmetic ones. You should not expect that high performance when using logical_right_shift() .
  • The function uses PHP_INT_MAX that is available since PHP 5.0.5.

Leave a Reply Cancel reply

You must be logged in to post a comment.

Proudly powered by WordPress. Theme: Flat 1.7.11 by Themeisle. CDN by PageCDN.
Website developed by Web Developers in Lahore..

Источник

Left and Right Function in PHP

We all know in Visual Basic or VBScript (including VBA i.e. Visual Basic for Application, the Microsoft Office Macro Programming Language), we can easily get the first few (leading) or last few (trailing) characters using left and right respectively. For example,

Dim s s = "Hello, World!" Msgbox Left(s, 3) ' Hel Msgbox Right(s, 3) 'ld!
Dim s s = "Hello, World!" Msgbox Left(s, 3) ' Hel Msgbox Right(s, 3) 'ld!

In PHP, there is no such functions defined. But we have substr which returns the portion of string given start index and optional length.

string substr ( string $string , int $start [, int $length ] )
function left($str, $length)  return substr($str, 0, $length); > function right($str, $length)  return substr($str, -$length); >

function left($str, $length) < return substr($str, 0, $length); >function right($str, $length)

The start index is from 0, i.e. the first character is at index zero. The start can be negative, which will count the position from the end of the string towards the begining of the string. If the length parameter is omitted, then the substring starts from the start position to the end of the string will be returned. If the length is given and it is positive, then at most length characters beginning with start will be returned.

PHP Function to Post to Twitter In order to post twits to Twitter using Twitter APIs, you would first need to…

Steem Reputation Format Function in PHP On Steem Blockchain, the reputation can be formatted in a logarithmetic (base 10) scale. Given…

How to Mask Email Addresses using PHP Function? For users privacy we don’t want to display the full email addresses — and we…

Ackermann Function The Ackermann function is mathematically defined as: The Ack function is well-defined total math function…

Filter out Spam Words using PHP Function Many situations we want to be able to detect if a post/comment is spam by…

A Simple PHP Function to Disable Google Fonts in WordPress Google Fonts are sometimes heavy-weight and slow to load especially in some regions e.g. mainland…

Simple PHP Function to Display Daily Bing WallPaper Bing uploads a daily wallpaper, and we can show today’s Bing wallpaper via the following…

How to Truncate a String in PHP? The following is a PHP Function that allows us to truncate a string (and optionally…

Two PHP Functions to Check HTTP Response Code (Status) of a URL using Curl Check the HTTP Reponse Status Code of a Request in PHP We can use the…

PHP Function to Check if a String is a Valid Domain Name via Regex Given a string e.g. «domain.com» we want to find out if it is a valid…

Источник

PHP 7: Left-to-right variable evaluation

code-icon

This is a story about how my own code broke a site in development after migrating from PHP 5 to PHP 7, and what I did to fix it.

On December 3 2015, PHP 7 was released. Along with significant speed increases, there were some breaking changes that make it not 100% backward compatible with PHP 5. Note that PHP 6 never actually existed (seriously), so that’s why it’s not mentioned here.

One of the breaking changes in PHP 7 was the following:

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases.

– PHP Manual [link]

Consider the following example:

$action = array( ‘callback’ => ‘my_function’, . );

Effectively, we are just invoking the function my_function in a fancy way that makes use of an array key/value pair. You may be thinking you’d never do this in the real world without additional context (if even then). I doubt that I will either in the future, even if the surrounding context makes it really tempting.

This isn’t actually an issue that PHP 7 seems to care about, though. It will do the above just fine.

However, if we add another variable layer into the mix, this is where we get the breaking changes introduced in PHP 7.

Consider the following code, which works fine in PHP 5:

$action = array( ‘callback’ => ‘my_function’, . );

$object = new Random_Object();

The PHP 5 result is identical to:

But now, when we upgrade to PHP 7 we’re going to have a fatal error!

In PHP 7, they decided to always interpret variable names left-to-right. Even though it breaks my code here, I’m actually glad that there is going to be a standard and not a mixed set of different rules.

The new way the above code will be interpreted in PHP 7 is as follows. I have broken it down into two logical steps, for illustrative purposes.

First, PHP looks directly at $object->$action (remember, left-to-right), which doesn’t even exist. It also doesn’t make sense as an expression because $action is an array, and we can’t use an array to access a property or method name for an object.

In effect, we have this being interpreted as an intermediate line of code:

// Notice: array to string conversion

Basically, $nothing_useful has been created indirectly for us by PHP, and its value is NULL. From here, we can’t expect anything good to happen. The result is that we are calling a function whose name is a NULL variable.

// Fatal error: function name must be a string

Luckily, this isn’t the worst thing to have to fix. As mentioned above, it makes me think that I should be way more careful about taking these types of shortcuts, and probably always use call_user_func or call_user_func_array in these kinds of scenarios.

Either way, it’s not too difficult to change the above code to make both PHP 5 and PHP 7 happy. We just have to be a little more careful with our handling of the array and the object:

$action = array( ‘callback’ => ‘my_function’, . );

$object = new Random_Object();

And that’s it! Just one extra line of code can make us both forward and backward compatible, and that’s a pretty good place to be.

Источник

Читайте также:  Простая web страница html
Оцените статью