Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, June 26, 2019

echo vs print Statement in PHP

There are two basic ways to get output in PHP:
  • echo
  • print

PHP echo statement

In PHP echo statement is a language construct and not a function, so it can be used without parentheses. But we are allowed to use parentheses with echo statement when we are using more than one arguments with it. The end of the echo statement is identified by the semi-colon (';').
We can use echo to output strings or variables. Below are some of the usage of echo statement in PHP:

Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. Below example shows how to display strings with PHP:

<?php
echo "Hello, This is echo vs print statement!";
?>

Output: Hello, This is echo vs print statement!

Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (,) operator.

<?php
echo "Hello!", "PHP", "World";
?>

Output: Hello! PHP World

PHP print statement

The PHP print statement is similar to the echo statement and can be used alternative to echo at many times. It is also language construct and so we may not use parentheses: print or print().
Like echo, print statement can also be used to print strings and variables. Below are some examples of using print statement in PHP:

Displaying String of Text: We can display strings with print statement in the same way  as we did with echo statements. The only difference is, we cannot display multiple strings separated by comma(,) with a single print statement.

<?php
print "Hello World!";
?>
Output: Hello World!


Difference Between echo and print Statement

  • echo can accept multiple arguments while print only accepts a single argument
  • echo doesn't have a return value while print always returns 1
  • echo is marginally faster than print


Thursday, July 20, 2017

New Features In PHP 7 That You Should Have A Look At

Now a days PHP is the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

New Features In PHP 7

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven't missed anything. Just to avoid the confusion with a dead project, PHP's latest release was named to PHP 7.

Let's take a deeper dive. Let's check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

  • Performance (Speed Improvement)
  • Scalar Type Declarations
  • Return Type Declarations
  • Combined Comparison Operator
  • Null Coalesce Operator
  • Anonymous Classes
  • Unicode Codepoint Escape Syntax
  • Closure call() Method
  • Filtered unserialize()
  • IntlChar Class
  • Expectations
  • Group use Declarations
  • Generator Return Expressions
  • Generator Delegation
  • Integer Division with intdiv()
  • session_start() Options
  • preg_replace_callback_array() Function
  • CSPRNG Functions
  • Support for Array Constants in define()
  • Reflection Additions

Let's take a look on every feature in details:

Performance (Speed Improvement)


The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. This is a result of refactoring the Zend Engine to use more compact data structures and less heap allocations/deallocations. The performance gains on real world applications will vary, though many applications seem to receive a ~100% performance boost - with lower memory consumption too! After it's release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase in server response times with PHP 7. For further details on benchmarks 


Scalar Type Declarations


PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.
By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

[code]
function getSum(float $a, float $b) {
   return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string "7 week" changed to float(7.0)
//with a "Notice: A non well formed numeric value encountered"
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)
[/code]

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding "strict_types=1" on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.
While using a strict type-declaration, if a mismatch occurs, a "Fatal Error" occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let's just cut the talk and take a look at an example with strict types turned on.

declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}

getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting "declare strict_type" to "1", the first two calls that pass a string produces a Fatal error: "Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given". With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declaration


The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

function getSum(float $a, float $b) : float {

}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

function getSum(float $a, float $b) : int {
    return $a + $b;
}

getSum(6, "7 week");
// changes int(6) to float(6.0) & string("7 week") to float(7.0)
// returns int(13);

getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)

getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)


Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits
These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

Combined Comparison Operator


The combined comparison operator (or spaceship operator) is a shorthand notation for performing three-way comparisons from two operands. It has an integer return value that can be either:


  • a positive integer (if the left-hand operand is greater than the right-hand operand)
  • 0 (if both operands are equal)
  • a negative integer (if the right-hand operand is greater than the left-hand operand)


The operator has the same precedence as the equality operators (==, !=, ===, !==) and has the exact same behaviour as the other loose comparison operators (<, >=, etc). It is also non-associative like them too, so chaining of the operands (like 1 <=> 2 <=> 3) is not allowed.

// compares strings lexically
var_dump('PHP' <=> 'Node'); // int(1)

// compares numbers by size
var_dump(123 <=> 456); // int(-1)

// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator


The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';


// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator

The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';

Anonymous Classes


Anonymous classes are useful when simple, one-off objects need to be created.

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }

    use SomeTrait;
});

/** Output:
object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}
*/
Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class' protected properties or methods, the anonymous class can extend the outer class. To use the private or protected properties of the outer class in the anonymous class, they must be passed through its constructor:

<?php

class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}

echo (new Outer)->func2()->func3(); // 6

Unicode Codepoint Escape Syntax


This enables a UTF-8 encoded unicode codepoint to be output in either a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}"; // ª
echo "\u{0000aa}"; // ª (same as before but with optional leading 0's)
echo "\u{9999}"; // 香

Closure call() Method


The new call() method for closures is used as a shorthand way of invoking a closure whilst binding an object scope to it. This creates more perfomant and compact code by removing the need to create an intermediate closure before invoking it.

class A {private $x = 1;}

// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX(); // 1

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A); // 1

Filtered unserialize()


This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar Class


The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

printf('%x', IntlChar::CODEPOINT_MAX); // 10ffff
echo IntlChar::charName('@'); // COMMERCIAL AT
var_dump(IntlChar::ispunct('!')); // bool(true)
In order to use this class, the Intl extension must be installed.

BC Breaks

Classes in the global namespace must not be called IntlChar.

Expectations


Expectations are backwards compatible enhancement to the older assert() function. They enable for zero-cost assertions in production code, and provide the ability to throw custom exceptions on error.

The assert() function's prototype is as follows:

void assert (mixed $expression [, mixed $message]);
As with the old API, if $expression is a string, then it will be evaluated. If the first argument is falsy, then the assertion fails. The second argument can either be a plain string (causing an AssertionError to be triggered), or a custom exception object containing an error message.

ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
With this feature comes two PHP.ini settings (along with their default values):


  • zend.assertions = 1
  • assert.exception = 0

zend.assertions has three values:


  • 1 = generate and execute code (development mode)
  • 0 = generate code and jump around at it at runtime
  • -1 = don't generate any code (zero-cost, production mode)

assert.exception means that an exception is thrown when an assertion fails. This is switched off by default to remain compatible with the old assert() function.

Group use Declarations


This gives the ability to group multiple use declarations according to the parent namespace. This seeks to remove code verbosity when importing multiple classes, functions, or constants that come under the same namespace.

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Generator Return Expressions


This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finishing yielding values.

// IIFE syntax now possible - see the Uniform Variable Syntax subsection in the Changes section
$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

// output:
// 1
// 2
// 3
Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator Delegation


Generator delegation builds upon the ability of being able to return expressions from generators. It does this by using an new syntax of yield from <expr>, where can be any Traversable object or array. This will be advanced until no longer valid, and then execution will continue in the calling generator. This feature enables yield statements to be broken down into smaller operations, thereby promoting cleaner code that has greater reusability.

function gen()
{
    yield 1;
    yield 2;

    return yield from gen2();
}

function gen2()
{
    yield 3;

    return 4;
}

$gen = gen();

foreach ($gen as $val)
{
    echo $val, PHP_EOL;
}

echo $gen->getReturn();

// output
// 1
// 2
// 3
// 4

Integer Division with intdiv()


The intdiv() function has been introduced to handle division where an integer is to be returned.

var_dump(intdiv(10, 3)); // int(3)

session_start() Options


This feature gives the ability to pass in an array of options to the session_start() function. This is used to set session-based php.ini options:

session_start(['cache_limiter' => 'private']); // sets the session.cache_limiter option to private
This feature also introduces a new php.ini setting (session.lazy_write) that is, by default, set to true and means that session data is only rewritten if it changes.

preg_replace_callback_array() Function


This new function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function (second parameter of preg_replace_callback()) to be polluted with lots of branching (a hacky method at best).

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

Function Signature:

string preg_replace_callback_array(array $regexesAndCallbacks, string $input);
$tokenStream = []; // [tokenName, lexeme] pairs

$input = <<<'end'
$a = 3; // variable initialisation
end;

// Pre PHP 7 code
preg_replace_callback(
    [
        '~\$[a-z_][a-z\d_]*~i',
        '~=~',
        '~[\d]+~',
        '~;~',
        '~//.*~'
    ],
    function ($match) use (&$tokenStream) {
        if (strpos($match[0], '$') === 0) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        } elseif (strpos($match[0], '=') === 0) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        } elseif (ctype_digit($match[0])) {
            $tokenStream[] = ['T_NUM', $match[0]];
        } elseif (strpos($match[0], ';') === 0) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        } elseif (strpos($match[0], '//') === 0) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    },
    $input
);

// PHP 7+ code
preg_replace_callback_array(
    [
        '~\$[a-z_][a-z\d_]*~i' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        },
        '~=~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        },
        '~[\d]+~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_NUM', $match[0]];
        },
        '~;~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        },
        '~//.*~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    ],
    $input
);

CSPRNG Functions


This feature introduces two new functions for generating cryptographically secure integers and strings. They expose simple APIs and are platform-independent.

Function signatures:

string random_bytes(int length);
int random_int(int min, int max);
Both functions will emit an Error exception if a source of sufficient randomness cannot be found.

Support for Array Constants in define()


The ability to define array constants was introduced in PHP 5.6 using the const keyword. This ability has now been applied to the define() function too:

define('ALLOWED_IMAGE_EXTENSIONS', ['jpg', 'jpeg', 'gif', 'png']);

Reflection Additions


Two new reflection classes have been introduced in PHP 7. The first is ReflectionGenerator, which is used for introspection on generators:

class ReflectionGenerator
{
    public __construct(Generator $gen)
    public array getTrace($options = DEBUG_BACKTRACE_PROVIDE_OBJECT)
    public int getExecutingLine(void)
    public string getExecutingFile(void)
    public ReflectionFunctionAbstract getFunction(void)
    public Object getThis(void)
    public Generator getExecutingGenerator(void)
}
The second is ReflectionType to better support the scalar and return type declaration features:

class ReflectionType
{
    public bool allowsNull(void)
    public bool isBuiltin(void)
    public string __toString(void)
}
Also, two new methods have been introduced into ReflectionParameter:

class ReflectionParameter
{
    // ...
    public bool hasType(void)
    public ReflectionType getType(void)
}
As well as two new methods in ReflectionFunctionAbstract:

class ReflectionFunctionAbstract
{
    // ...
    public bool hasReturnType(void)
    public ReflectionType getReturnType(void)

}

These were the new features in PHP 7.

Wednesday, May 3, 2017

Top Laravel Interview Questions with Answers

Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax. Now a days Laravel is very popular PHP framework so mostly companies works on this framework. Here we are listing top Laravel interview questions with answers.



1. What is Laravel?
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax.

2. What are Advantages of Laravel?

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel
3. Explain about Laravel Project?
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.

4. What are the feature of Laravel 5.4?
  • Introducing Laravel Dusk
  • Introducing Laravel Mix 
  • New Markdown Mail in Laravel 5.4 
  • Slots and Components in Laravel 5.4
  • Real-time (automatic) Facades in Laravel 5.4
  • TrimStrings and ConvertEmptyStringsToNull middleware in Laravel 5.4
  • JSON localization files in Laravel 5.4
  • Binding method calls in the service container in Laravel 5.4 
  • The --model flag for creating better resourceful controllers in Laravel 5.4
  • Laravel Collections' updates--higher order messaging and new methods--in Laravel 5.4 
5. Compare Laravel with Codeigniter?
        Laravel                                                                                        Codeigniter
Laravel is a framework with expressive, CodeIgniter is a powerful PHP                       elegant syntax                                                                    framework
Development is enjoyable, creative                                 Simple and elegant toolkit to create full-         experience                                                                         featured web applications.
Laravel is built for latest version of PHP                         Codeigniter is an older more mature                                                                                                         framework
It is more object oriented compared                                 It is less object oriented compared to               to CodeIgniter.                                                                  Laravel.
Laravel community is still small, but it is                        Codeigniter community is large.
growing very fast.

6. What are Bundles,Reverse Routing and The IoC container ?

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

Also Read: PHP Interview Questions with Answers

7. How to set Database connection in Laravel?
Database configuration file path is : config/database.php
Following are sample of database file

[code]  'mysql' => [
    'read' => [
        'host' => 'localhost',
    ],
    'write' => [
        'host' => 'localhost'
    ],
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
], [/code]

8. How to enable the Query Logging?
[code] DB::connection()->enableQueryLog();[/code]

9. How to use select query in Laravel?
[code] $users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
    foreach($users as $user){

    }
} [/code]

9. How to use Insert Statement in Laravel?
[code] DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]); [/code]

10. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]); [/code]

11. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]);[/code]

12. How to use delete Statement in Laravel?
[code] DB::delete('delete from  users where id = ?', [1015]); [/code]

13. Does Laravel support caching?
Yes, Its provides.

Also Read: Top Zend Framework Interview Questions with Answers

14. I've already created a database table that I want to use with Laravel's ORM. How would I setup a class to do that?
Laravel's ORM is called Eloquent. There are two main ways to go about doing this. The first one would be to physically write a class:
[code] <?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'students';
}[/code]

And the second one would be to use the artisan CLI, which generates a class:
[code] php artisan make:model students [/code]

15. Laravel comes with a PHP CLI called artisan. What is your favorite artisan command?
There are so many things that the CLI does out of the box. Even if they don't have a favorite command, they should be able to explain what some of them do. Here's a sample of available top-level commands:
Available commands:
  •   clear-compiled      Remove the compiled class file
  •   down                Put the application into maintenance mode
  •   env                 Display the current framework environment
  •   help                Displays help for a command
  •   inspire             Display an inspiring quote
  •   list                Lists commands
  •   migrate             Run the database migrations
  •   optimize            Optimize the framework for better performance
  •   serve               Serve the application on the PHP development server
  •   tinker              Interact with your application
  •   up                  Bring the application out of maintenance mode
16. Laravel 5 has built in CSRF protection on every route. How would I go about turning that off?
  Hopefully they mention that CSRF protection is important, but since we're asking them to turn it off they might not mention it which is OK. You'd easily turn it off by going into Kernel.php and removing it from the middleware stack that is ran on every route.

This is also a good place to ask about middleware in general and make sure they both understand what middleware is and why it's important.

17. List out some benefits of Laravel over other Php frameworks.
  • Setup and customization process is  easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation. 
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.
Also Read: WordPress Interview Questions And Answers

18. What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.

19. How to install laravel via composer ?

 composer create-project laravel/laravel your-project-name version

 20. How to check laravel current version ?
 You can check the current version of your Laravel installation using the --version option of artisan command Usages:
 [code] php artisan --version [/code]

21. What is php artisan. List out some artisan command ?

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command:
  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan --versian
  • php artisan make modal modal_name
  • php artisan make controller controller_name 
22. Explain Events in laravel ?

An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation,that allow us  to subscribe and listen for events in our application.
Below are some events examples in laravel :
A new user has registered
A new comment is posted
User login/logout
New product is added.

23. How to enable query log in laravel?

Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

Also Read: Most Popular Codeigniter Interview Questions with Answers

24. How to turn off CRSF protection for a route in Laravel?

In "app/Http/Middleware/VerifyCsrfToken.php"
 //add an array of Routes to skip CSRF check
  private $exceptUrls = ['controller/route1', 'controller/route2'];
 //modify this function

[code]public function handle($request, Closure $next) {
 //add this condition foreach($this->exceptUrls as $route) {
 if ($request->is($route)) {
  return $next($request);
 }
}
return parent::handle($request, $next);
}[/code]

25. How can you get users IP address  in Laravel ?

[code] public function getUserIp(Request $request){
          // Getting ip address of remote user

            return $user_ip_address=$request->ip();
}[/code]

26. How to use custom table in Laravel Modal We can use custom table in laravel by overriding protected $table property of Eloquent. Below is sample uses

[code] class User extends Eloquent{
 protected $table="my_user_table";

}[/code]

27. How to define Fillable Attribute in Laravel Modal ?
You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

[code] Class User extends Eloquent{

protected $fillable =array('id','first_name','last_name','age');


}[/code]

28. In which directory controllers are located in Laravel ?

We kept all controllers in
app/http/Controllers directory

29. What does PHP compact function do ?
PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.

30. Define ORM ?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

Also Read: Apache Solr Interview Questions and Answers

31. How to create a record in Laravel using eloquent? 

To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage

[code] public function saveProduct(Request $request )
 $product = new product;
 $product->name = $request->name;
 $product->description = $request->name;
 $product->save(); [/code]

 32. What is the purpose of the Eloquent cursor() method in laravel?

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage. Example Usage

[code] foreach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff } [/code]

33. How to get Logged in user info in laravel ?

Auth::User() function is used to get Logged in user info in laravel. Usage:

[code] if(Auth::check()){

$loggedIn_user=Auth::User();
dd($loggedIn_user);

} [/code]


34. What are Closures in laravel ?
Closures is an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.


Tuesday, May 2, 2017

Most Popular Codeigniter Interview Questions with Answers

CodeIgniter is an open-source software rapid development web framework, for use in building dynamic web sites with PHP. CodeIgniter is popular model–view–controller (MVC) development pattern. CodeIgniter is most often noted for its speed when compared to other PHP frameworks. Today mostly web development happens in CodeIgniter framework. In PHP interview a lot of questions are asked from CodeIgniter. Here we are listing most popular CodeIgniter Interview Questions with Answers.


1. What is Codeigniter?

Codeigniter is the most popular open source PHP framework. It is very simple and lightweight. It can be used to develop any kind of web project from small website to large scale of application.

2. What are the most prominent features of CodeIgniter?

A list of most prominent features of CodeIgniter:

It is an open source framework and free to use.
It is extremely light weighted.
It is based on Model View Controller (MVC) pattern.
It has full featured database classes and support for several platforms.
It is extensible. You can easily extend system by using your own libraries, helpers etc.
Excellent documentation.
Security and XSS Filtering
File uploading, session management, pagination, data encryption
Flexible URI Routing
Zip encoding class
Error logging
Full page caching
Localization

3. Explain the folder structure of CodeIgniter.

If you download and unzip CodeIgniter, you will get the following file structure/folder structure:


Application     
cache
Config
Controllers
core
errors
helpers
hooks
language
libraries
logs
models
thirdparty
views

system

core
database
fonts
helpers
language
libraries

4. How to access config variable in codeigniter? 

[code] $this->config->item('variable name'); [/code]

5. How to unset session in codeigniter?

[code] $this->session->unsetuserdata('somename');  [/code]

6. How do you get last insert id in codeigniter? 

 [code]  $this->db->insertid(); [/code]


7. Why use Hooks in Codeigniter

Hooks are the special feature of Codeigniter that allows to change the inner functionality of framework without making any change in core files of framework. The Hooks are defined in application/config/hooks.php.

8. What are different types of hook points in CodeIgniter?

A list of different types of hook points in CodeIgniter:

post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

9. How can you load a view in CodeIgniter?

View can't be accessed directly. It is always loaded in the controller file. Following function is used to load a view page:

[code]  $this->load->view('page_name');  [/code]


10. What is routing in Codeigniter?

Instead of accessing files directly from browser, Routing enables to serve files differently. Routing is an important part of Codeigniter that enables to customize default URL pattern according to requirement to use your own and it redirect automatically to matched URL pattern by specified controller and function.

11. How to load Model in CodeIgniter?

Models are PHP classes that are designed to work with information in your database. In CodeIgniter, Model classes are stored in your application/models/ folder. The models will typically be loaded and called from within your controller functions. To load a model you will use the following function:
[code] $this->load->model('Model_name'); [/code]

12. What are the Helpers in CodeIgniter?

The Helpers are the group of functions in a specific category that helps to perform particular functions. There are many helpers in CodeIgniter that you can use according to your requirement. The major CodeIgniter helpers are URL Helpers that assist in creating link, Form Helpers that help you create form elements, Text Helpers to perform various text formatting routines, Cookie Helpers to set and read cookies, File Helpers to help you deal with files etc.

13. List out different types of hook point in Codeigniter?

Different types of hook point in Codeigniter includes
post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

14. Mention what are the security parameter for XSS in CodeIgniter?

Codeigniter has got a cross-site scripting hack prevention filter. This filter either runs automatically or you can run it as per item basis, to filter all POST and COOKIE data that come across.  The XSS filter will target the commonly used methods to trigger JavaScript or other types of code that attempt to hijack cookies or other malicious activity. If it detects any suspicious thing or anything disallowed is encountered, it will convert the data to character entities.

15. Explain how you can link images/CSS/JavaScript from a view in code igniter?

In HTML, there is no Codeigniter way, as such it is a PHP server side framework. Just use an absolute path to your resources to link images/CSS/JavaScript from a view in CodeIgniter
/css/styles.css

/js/query.php

/img/news/235.gpg

16. Explain what is inhibitor in CodeIgniter?

For CodeIgniter, inhibitor is an error handler class, using the native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.

17. Mention what is the default URL pattern used in Codeigniter framework?

Codeigniter framework URL has four main components in default URL pattern.  First we have the server name and next we have the controller class name followed by controller function name and function parameters at the end. Codeigniter can be accessed using the URL helper. For example http://servername/controllerName/controllerFunction/parameter1/parameter2.

18. Explain how you can extend the class in Codeigniter?

To extend the native input class in CodeIgniter, you have to build a file named application/core/MY_Input.php and declare your class with
[code] Class MY_Input extends CI_Input {

} [/code]

19.How can you load multiple helper files?

To load multiple helper files, specify them in an array,
[code] $this->load->helper(  
array('helper1', 'helper2', 'helper3')  
);  [/code]

20. Explain how you can prevent CodeIgniter from CSRF?

There are several ways to protect CodeIgniter from CSRF, one way of doing is to use a hidden field in each form on the website.  This hidden field is referred as CSRF token; it is nothing but a random value that alters with each HTTP request sent. As soon as it is inserted in the website forms, it gets saved in the user’s session as well.  So, when the form is submitted by the users, the website checks whether it is the same as the one saved in the session. If it is same then, the request is legitimate.

21. Explain how you can enable CSRF (Cross Site Request Forgery) in CodeIgniter?

You can activate CSRF (Cross Site Request Forgery) protection in CodeIgniter by operating your application/config/config.php file and setting it to
[code] $config [ 'csrf_protection'] = TRUE; [/code]
If you avail the form helper, the form_open() function will insert a hidden csrf field in your forms automatically


22. What are CodeIgniter drivers?

These are special type of library that has a parent class and many child classes. These child classes have access to the parent class, but not to their siblings. Drivers are found in system/libraries folder.

23. How to initialize a driver in CodeIgniter?

To initialize a driver, write the following syntax,
[code] $this->load->driver('class_name');  [/code]

Monday, October 17, 2016

Some Common Mistakes that PHP Developers Make

One of the best things about PHP is that it is  a great language to just 'dive into'. Thanks to its wide-ranging popularity, anyone with the ability to hit "Search" on Google can quickly create a program. However, this also lends to a major criticism of PHP, i.e. it is almost too easy to find and reproduce bad code.

Here are some mistakes that any PHP programmer, regardless of skill level, might make at any given time. Some of the mistakes are very basic, but unfortunately, they can trip up even the best PHP programmer! Other mistakes are hard to spot (even with strict error reporting). However, all  these mistakes have one thing in common: They are  easy to avoid.!


Single quotes, double quotes
It's easy to just use double quotes when concatenating strings because it parses everything neatly without having to deal with escaping characters and using dot values. However, using single quotes has considerable performance gains, as it requires less processing.

Consider this string:
[code]
$boo = 'everyone';
$foo = 'hello $boo';
$bar = "hello $boo";
[/code]


$foo outputs to "hello $boo" and $bar gives us "hello everyone". That's one less step that PHP has to process. It's a small change that can make significant gains in the performance of the code.

NOT Using database caching
If you use a database in your PHP application, it is strongly advised that you at least use some sort of database caching. Memcached has emerged as the most poplar caching system, with mammoth sites like Facebook endorsing the software.


Memcached is free and can provide very significant gains to your software. If your PHP is going into production, it is strongly advised to use the caching system.

Not Using E_ALL Reporting

Error reporting is a very handy feature in PHP, and if you're not already using it, you should really turn it on. Error reporting takes much of the guesswork out of debugging code, and speeds up your overall development time.

While many PHP programmers may use error reporting, many aren't utilizing the full extent of error reporting. E_ALL is a very strict type of error reporting, and using it ensures that even the smallest error is reported. (That's a good thing if you're wanting to write great code.)

When you're done developing your program, be sure to turn off your reporting, as your users probably won't want to see a bunch of error messages on pages that otherwise appear fine. (Even with the E_ALL error reporting on they hopefully won't see any errors anyway, but mistakes do happen.)

Not Escaping Entities
Many times PHP programmers are too trusting with data, especially data generated by user. It's imperative to sanitize data before it goes into any sort of storage, like a database.

Source Rally shows us how to correctly escape entities in things like forms. Instead of using this:

echo $_GET['username'];

You can validate the data by using htmlspecialchars() (or htmlentities()) like so:

echo htmlspecialchars($_GET['username'], ENT_QUOTES);

Using Wrong Comparison Operators
While comparison operators are an extremely basic part PHP programming, mixing these up in your code is certain to bork your program. As the German proverb states, the devil is in the details!


Being familiar with the often-misused operators like =, ==, != , are absolutely critical to PHP programming. Taking the time to really understand the differences will greatly speed up your programming and yield less bugs to debug.

Not using PDO
Don’t get me wrong, mysqli is (quite literally) generations ahead of the ancient mysql extension. It’s kept up to date, secure, reliable and fast. However, it’s mysql specific. Using PDO instead would let you use some wonderfully practical object oriented syntax, and would prepare you for tango with other SQL databases like PostgreSQL, MS SQL, and more. What’s more, PDO will let you use named parameters, a feature so useful, few people can imagine going to anything else after having taken proper advantage of it.
Last but not least, there’s this: you can inject fetched data directly into a new object, which is a delightful timesaver in large projects.

Not rewriting URLs
Another commonly ignored and easy to fix issue. URLs like mypage.com/index.php?p=43&g=24 are just not acceptable in this day and age. Due to it being incredibly difficult to write a good URL rewriting guide that would cover every server and framework out there, almost every framework has a guide on how to set up clean URLs (Laravel, Phalcon, Symfony, Zend) and any that don’t just aren’t worth using – they obviously don’t care about modern practices.

Not optimizing your queries
99% of PHP performance problems will be caused by the database, and a single bad SQL query can play havoc with your web application. MySQL’s EXPLAIN statement, the Query Profiler, and many other tools can help you find that rogue SELECT.

Using * in SELECT queries
Never use * to return all columns in a table–it's lazy. You should only extract the data you need. Even if you require every field, your tables will inevitably change.

Under or over-indexing
As a general rule of thumb, indexes should be applied to any column named in the WHERE clause of a SELECT query.

For example, assume we have a usertable with a numeric ID (the primary key) and an email address. During log on, MySQL must locate the correct ID by searching for an email. With an index, MySQL can use a fast search algorithm to locate the email almost instantly. Without an index, MySQL must check every record in sequence until the address is found.


It is tempting to add indexes to every column, however, they are regenerated during every table INSERT or UPDATE. That can hit performance; only add indexes when necessary.

Forgetting to back up
It may be rare, but databases fail. Hard disks can stop. Servers can explode. Web hosts can go bankrupt. Losing your MySQL data is catastrophic, so ensure you have automated backups or replication in place.


Saturday, May 21, 2016

PHP Tips and Tricks to Improve Your Programming Skills

Guys if you love to PHP programming. Listed below are some excellent techniques that PHP developers should learn and use every time they program. They can improve their PHP programming skills to follow these tricks.


Avoid the use of printf function
Unlike print and echo, printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables.
<?php
echo 'FinalResult:', $result;  
// is better than
printf("FinalResult.%s", $result );
?>

echo is faster than print
PHP is giving some sting functions to printing output into browser and we are often using print() and echo() function.
Print() function behavior like the other function in common and having return value integer 1. Thus, print() can used as part of expression which more complex. Meanwhile, echo() is able to accept more than one parameters all at once, and does not having return value.
<?php
print() 'string 1';
echo 'string 1';
// using some parameters
echo 'string 1', "string 2", '...';
?>

echo() function string will execution more faster than print(). This differentiate caused by will return status (integer) which expose what process has done or not.

Loops and Counting
Here are some ways to make your loops and counting a bit more efficient.
Use pre-calculations and set the maximum value for your for-loops before and not in the loop. This means you are not calling the count() function on every loop.

$max = count($array);
for ($i = 0; $i < $max; $i++)
//is faster than
for ($i = 0; $i < count($array); $i++)
When checking the length of strings:
Use isset where possible in replace of strlen. (cite)
if (!isset($foo{5})) { echo "Foo is too short"; }
//is faster than
if (strlen($foo) < 5) { echo "Foo is too short"; }


Single Quotes vs Double Quotes
You may or may not think about this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.
    <?php
         echo 'hello world in techbowl';
    ?>
    <?php
         echo "hello world in techbowl";
    ?>
These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let’s take an example.
    <?php
   
          $example = 'hello world in techbowl';
   
          echo '$example'; // outcome will be $example
   
          echo "$example"; // outcome will be hello world in techbowl
    ?>
As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead.
Obviously on a small scale this means nothing but if you have a loop that iterates 1000 or more times you might start to see the benefits of single quotes in a performance sense.

When incrementing:
Use pre-incrementing where possible as it is 10% faster.
++$i;
//is faster than
$i++;
And
Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Accessing arrays
For Example:  $result['post_id'] is 7 times faster than $result[post_id]

Avoid functions inside loops
Try to use functions outside loops. Otherwise the function may get called each time and obviously it will affect performance.
<?php

    /*  loop with a count() inside the control block will be
        executed on EVERY loop iteration.
    */
    $count = count( $array );  
    for( $i = 0; $i < $count; $i++ )  
    {  
        // do something here
    }  
     
    // is better than          
    for( $i = 0; $i < count( $array ); $i++ )  
    {  
        // do something here
    }
?>
It's even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.
<?php
    foreach ($array as $i) {
        // do something  
    }
?>


Use absolute paths in includes and requires
It means less time is spent on resolving the OS paths.
include('/var/www/html/your_app/test.php');
//is faster than
include('test.php');
require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.

true is faster than TRUE
This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lower cased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

Use isset() instead of strlen() function
<?php
$str = "45e23";
if (!isset($str{5})) {
    echo 'String must be at least 5 characters<br />';
}
if (strlen($str) < 5){
    echo 'String must be at least 5 characters;
}
?>
isset() needs little more time than strlen() because isset() is a language construct.
When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $str[5] is the sixth character in $str)

Use ternary operators instead of if, else
Ternary operators can be very helpful and clean up the code, but don’t over complicate them otherwise your code might become inundated with large amounts of complex ridiculousness.
<?php
$name = (!empty($_GET['name'])? $_GET['name'] .'techbowlarticle');
?>

one-liner to convert XML into associative array.
<?php
$arr = json_decode(json_encode(simplexml_load_string($xml, null, LIBXML_NOCDATA)), true);
?>


Maintain debugging environment in your application

During development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. But its a good idea to let everything stay and help in the long run

On your development machine you can do this :

[code]
define('ENVIRONMENT' , 'development');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }  
}
[/code]

And on the server you can do this :\
[code]
define('ENVIRONMENT' , 'production');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }  

}
[/code]

Omit the closing php tag if it is the last thing in a script
Let's have a look on below code
<?php

echo "Hello";

//Now dont close this tag

This will save you lots of problem. Lets take an example :

A class file super_class.php
<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}
?>
//super extra character after the closing tag
Now index.php

require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data
And you will get Headers already send error. Why ? because the "super extra character" has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.

Hence make it a habit to omit the closing tag :

<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}

//No closing tag
That's better.


So there were few tricks and tips to improve the PHP programming skills, hope you will follow these and love these.


Wednesday, May 11, 2016

Interesting and Strange Facts about PHP, Every Developer should know

Are you getting started with PHP ? Then you gotta know these facts about php. It will help to generate interest in yourself and encourage others to learn php.


Many of these facts are reason for PHP being so popular.
  • PHP originally stood for Personal Home Page.
  • PHP which is now officially known as 'Hypertext Preprocessor' was released in the year 1995.
  • Initially written as a set of Common Gateway Interface (CGI) in 'C' (1994).
  • PHP was originally designed to replace a set of Perl scripts to maintain his Personal Home Pages (also known as PHP).
  • PHP was originally created by Rasmus Lerdorf in 1995. He wrote the original Common Gateway Interface (CGI) binaries.
  • Zeev Suraski and Andi Gutmans, two developers at the Technion IIT, rewrote the parser in 1997 and formed the base of PHP 3.
  • PHP 3 was official launched in June 1998.
  • Suraski and Gutmans rewrote the PHP 3's core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel.
  • On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released.
  • The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.
  • On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 introduced full featured object-oriented programming support. It was there in PHP 3 and PHP 4 but only the basic features.
  • PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) due to restrictions on the use of the term PHP.
  • PHP was originally designed to create dynamic and more interactive web pages. It is the most widely-used, open-source and general-purpose scripting language.
  • It is possible to use PHP in almost every operating system. PHP can be used in all major operating systems including Linux, Microsoft Windows, Mac OS X, and RISC OS.
  • PHP uses procedural programming or object oriented programming and also a mixture of them.
  • PHP is installed on over 20 million websites and 1 million web servers. (PHP: 244M sites, 2.1M IP addresses) http://php.net/usage.php
  • 75% of Web 2.0 sites are built in PHP. PHP is used by 81.7% of all the websites whose server-side programming language we know.
  • There are about 5 million PHP developers worldwide.
  • The latest release of PHP till now is 7.0.6. It was released on April 29, 2016. During 2014 and 2015, a new major PHP version was developed, which was numbered PHP 7. The numbering of this version involved some debate. While the PHP 6 Unicode experiment had never been released, several articles and book titles referenced the PHP 6 name, which might have caused confusion if a new release were to reuse the name. After a vote, the name PHP 7 was chosen
  • Some of the biggest online brands, such as Facebook, ProProfs, Digg, Friendster, Flickr, Technorati, and Yahoo! are powered by PHP
Popular sites using PHP
  • Facebook.com
  • Wikipedia.org
  • Qq.com
  • Taobao.com
  • Wordpress.com
  • Sina.com.cn
  • Vk.com
  • Mail.ru
  • Weibo.com
Strange PHP Facts about PHP

Floating Point Imprecision

Most of you probably know that floating-point numbers cannot really represent all real numbers. Besides, some operations between two well represented numbers can lead to surprising situations. This is because the finite precision with which computers represent numbers and so it affects not just PHP but all the programming languages. Inaccuracies in floating point problems have been given programmers headaches from the beginning of the discipline.
Let's look at this very small snippet:

echo (int) ((0.1 + 0.7) * 10);

What do you think will be the result? If you guessed 8, you'd be wrong I'm sorry, This code will actually print 7. 

Now let's see why this happens. The first operation executed is:

0.1 + 0.7 // result is 0.79999999999

The result of the arithmetic expression is stored internally as 0.7999999, not 0.8 due to the precision issue, and this is where the problem starts.

The second operation executed is:

0.79999999 * 10 = 7.999999999

This operation works well but preserves the error.

The third and last operation executed is:

(int) 7.9999999 // result is 7

The expression makes use of an explicit cast. When a value is convert to int, PHP truncates the decimal portion of the number which makes the result 7.

There are two interesting things to note here:
  • If you cast the number to float instead of int, or if you don’t cast at all, you'll get 8 as result as you expected.
  • Although the CPU doesn’t know, and we actually we got this error due to its imprecisions, it's working accordingly to the mathematics paradox that asserts 0.999… is equal to 1.

How PHP "Increments" Strings

During our everyday work we write instructions that perform incrementing/decrementing operations like these:

$a = 5;
$b = 6;
$a++;
++$b;

Everyone easily understands what’s going on with those statements. But given the following statements, guess what will be the output:

$a = 1;
$b = 3;
echo $a++ + $b;
echo $a + ++$b;
echo ++$a + $b++;

Did you write down your answers? Good. Let's check all.

4
6
7
Not too difficult, right? Now let’s raise the bar a little. Have you ever tried to increment strings? Try to guess what the output will be for the following:

$a = 'fact_2';
echo ++$a;

$a = '2nd_fact';
echo ++$a;

$a = 'a_fact';
echo ++$a;

$a = 'a_fact?';
echo ++$a;

It’s not so easy this time, is it. Let’s uncover the answers.

fact_3
2nd_facu
a_facu
a_fact?
Surprised? Using an increment operator on a string that ends with a number has the effect of increasing the letter (the one following it in the alphabet, e.g. t -> u). Regardless if the string starts with digits or not, the last character is changed. But there is no effect if the string ends with a non-alphanumeric character.

This is well documented by the official documentation about the incrementing/decrementing operators but most of you may not have read it because you probably thought nothing special was there. I must admit I thought the same until a short time ago.

The Mystery of Value Appearance

You’re a real array master in PHP, admit it. Don’t be shy. You already know everything about how to create, manage, and delete arrays. Nonetheless, the next example might surprise you at first sight.

Often you work with arrays and need to search if a given value is in an array. PHP has a function for this, in_array(). Let’s see it in action:

$array = array(
  'isReady' => false,
  'isPHP' => true,
  'isStrange' => true
);
var_dump(in_array('techbowl.in', $array));

What will be the output? Place your bets and let’s check it.

true
Isn’t this a little bit strange? We have an associative array where its values are all boolean and if we search for a string, we got true. Has this value magically appeared? Let’s see another example.

$array = array(
  'count' => 1,
  'references' => 0,
  'ghosts' => 1
);
var_dump(in_array('pawan', $array));

And what we get is…

true
Once again the in_array() function returns true. How is this possible?

You’re experiencing one of both best and worst, loved and hated PHP features. PHP isn’t strongly typed and this is where the error starts. In fact, all the following values, if compared in PHP, are considered the same unless you use the identity operator:

0
false
""
"0"
NULL
array()
By default, the in_array() function uses the loose comparison, a non-empty ("") and non-zero-filled ("0") string is equal to true and to all non-zero numbers (like 1). Hence, in the first example we got true because 'techbowl.in' == true, while in the second we have 'aurelio' == 0.

To solve the problem you've to use the third and optional parameter of in_array() that allows you to compare the values strictly. So, if we write:

$array = array(
  'count' => 1,
  'references' => 0,
  'ghosts' => 1
);
var_dump(in_array('pawan', $array, true));

we'll finally get false as we expect!