LARAVEL Interview Questions and Answers
LARAVEL Interview Questions and Answers
LARAVEL Interview Questions and Answers
● Posted by Sharad Jaiswal
● Laravel is free open source “PHP framework” based on MVC design
pattern.
● It is created by Taylor Otwell. Laravel provides expressive and elegant
syntax that helps in creating a wonderful web application easily and
quickly.
● 0
● Q2.
● What are pros and cons of using Laravel Framework?
● Posted by Sharad Jaiswal
● Pros of using Laravel Framework
Laravel framework has in-built lightweight blade template
○
engine to speed up compiling task and create layouts with
dynamic content easily.
○ Hassles code reusability.
○ Eloquent ORM with PHP active record implementation
○ Built in command line tool “Artisan” for creating a code skeleton ,
database structure and build their migration
● Cons of using laravel Framework
○ Development process requires you to work with standards and
should have real understanding of programming
○ Laravel is new framework and composer is not so strong in
compare to npm (for node.js), ruby gems and python pip.
○ Development in laravel is not so fast in compare to ruby on rails.
○ Laravel is lightweight so it has less inbuilt support in compare to
django and rails. But this problem can be solved by integrating
third party tools, but for large and very custom websites it may be
a tedious task
● 0
● Q3.
● Explain Events in laravel ?
● Posted by Sharad Jaiswal
● An event is an action or occurrence recognized by a program that may
be handled by the program or code. Laravel events provides a simple
observer implementation, that allowing you to subscribe and listen for
various events/actions that occur in your application.
● All Event classes are generally stored in the app/Events directory, while
their listeners are stored in app/Listeners of your application.
Q4.
● Explain validations in laravel?
● Posted by Sharad Jaiswal
● In Programming validations are a handy way to ensure that your
data is always in a clean and expected format before it gets into
your database. Laravel provides several different ways to validate
your application incoming data.By default Laravel’s base
controller class uses a ValidatesRequests trait which provides a
convenient method to validate all incoming HTTP requests
coming from client.You can also validate data in laravel by
creating Form Request.
● click here read more about data validations in Laravel.
● 0
● Q5.
● How to install laravel via composer ?
● Posted by Sharad Jaiswal
● You can install Laravel via composer by running below command.
● composer create-project laravel/laravel your-project-name
version
● Also Read Core PHP Interview Questions and Answers for 2018
● 0
● Q6.
● List some features of laravel 5.0 ?
● Posted by Sharad Jaiswal
○ Inbuilt CRSF (cross-site request forgery ) Protection.
○ Inbuilt paginations
○ Reverse Routing
○ Query builder
○ Route caching
○ Database Migration
○ IOC (Inverse of Control) Container Or service container.
● 0
● Q7.
● What is PHP artisan. List out some artisan
commands ?
● Posted by Sharad Jaiswal
● 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 artisan command:-
○ php artisan list
○ php artisan help
○ php artisan tinker
○ php artisan make
○ php artisan –versian
○ php artisan make model model_name
○ php artisan make controller controller_name
● 0
● Q8.
● List some default packages provided by Laravel
5.6 ?
● Posted by Sharad Jaiswal
● Below are list of some official/ default packages provided by
Laravel 5.6
○ Cashier
○ Envoy
○ Passport
○ Scout
○ Socialite
○ Horizon
● 0
● Q9.
● What are named routes in Laravel?
● Posted by Sharad Jaiswal
● Named routing is another amazing feature of Laravel framework.
Named routes allow referring to routes when generating
redirects or Urls more comfortably.
● You can specify named routes by chaining the name method
onto the route definition:
● Route::get('user/profile', function () {
//
})->name('profile');
● 0
● Q10.
● What is database migration. How to create
migration via artisan ?
● Posted by Sharad Jaiswal
● Migrations are like version control for your database, that’s allow
your team to easily modify and share the application’s database
schema. Migrations are typically paired with Laravel’s schema
builder to easily build your application’s database schema.
● Use below commands to create migration data via artisan.
● // creating Migration
php artisan make:migration create_users_table
● 0
● Q11.
● What are service providers ?
● Posted by Sharad Jaiswal
● Service Providers are central place where all laravel application is
bootstrapped . Your application as well all Laravel core services
are also bootstrapped by service providers.
● All service providers extend the
Illuminate\Support\ServiceProvider class. Most service providers
contain a register and a boot method. Within the register
method, you should only bind things into the service container.
You should never attempt to register any event listeners, routes,
or any other piece of functionality within the register method.
● You can read more about service provider from h
ere
● 0
● Q12.
● Explain Laravel’s service container ?
● Posted by Sharad Jaiswal
● One of the most powerful feature of Laravel is its Service
Container. It is a powerful tool for resolving class dependencies
and performing dependency injection in Laravel.
● Dependency injection is a fancy phrase that essentially means
class dependencies are “injected” into the class via the
constructor or, in some cases, “setter” methods.
● 0
● Q13.
● What is composer ?
● Posted by Sharad Jaiswal
● Composer is a tool for managing dependency in PHP. It allows
you to declare the libraries on which your project depends on and
will manage (install/update) them for you.
● Laravel utilizes Composer to manage its dependencies.
● 0
● Q14.
● What is dependency injection in Laravel ?
● Posted by Sharad Jaiswal
● In software engineering, dependency injection is a technique
whereby one object supplies the dependencies of another object.
A dependency is an object that can be used (a service). An
injection is the passing of a dependency to a dependent object (a
client) that would use it. The service is made part of the client’s
state.[1] Passing the service to the client, rather than allowing a
client to build or find the service, is the fundamental requirement
of the pattern.
● https://en.wikipedia.org/wiki/Dependency_injection
● 0
● Q15.
● What are Laravel Contract’s ?
● Posted by Sharad Jaiswal
● Laravel’s Contracts are nothing but a set of interfaces that define
the core services provided by the Laravel framework.
● Read more about laravel Contract’s
● 0
● Q16.
● Explain Facades in Laravel ?
● Posted by Sharad Jaiswal
● Laravel Facades provides a static like an interface to classes that
are available in the application’s service container. Laravel
self-ships with many facades which provide access to almost all
features of Laravel ’s. Laravel facades serve as “static proxies” to
underlying classes in the service container and provide benefits of
a terse, expressive syntax while maintaining more testability and
flexibility than traditional static methods of classes. All of Laravel’s
facades are defined in the Illuminate\Support\Facades
namespace. You can easily access a facade like so:
●
use Illuminate\Support\Facades\Cache;
Route::get('/cache', function () {
return Cache::get('key');
});
● 0
● Q17.
● What are Laravel eloquent?
● Posted by Sharad Jaiswal
● Laravel’s Eloquent ORM is simple Active Record implementation
for working with your database. Laravel provide many different
ways to interact with your database, Eloquent is most notable of
them. Each database table has a corresponding “Model” which is
used to interact with that table. Models allow you to query for
data in your tables, as well as insert new records into the table.
● Below is sample usage for querying and inserting new records in
Database with Eloquent.
●
// Querying or finding records from products table where
tag is 'new'
$products= Product::where('tag','new');
// Inserting new record
$product =new Product;
$product->title="Iphone 7";
$product->price="$700";
$product->tag='iphone';
$product->save();
● 0
● Q18.
● How to enable query log in Laravel ?
● Posted by Sharad Jaiswal
● Use the enableQueryLog method to enable query log in Laravel
●
DB::connection()->enableQueryLog();
You can get array of the executed queries by using
getQueryLog method:
$queries = DB::getQueryLog();
● 0
● Q19.
● What is reverse routing in Laravel?
● Posted by Sharad Jaiswal
● Laravel reverse routing is generating URL's based on route
declarations. Reverse routing makes your application so much
more flexible. It defines a relationship between links and Laravel
routes. When a link is created by using names of existing routes,
appropriate Uri's are created automatically by Laravel. Here is an
example of reverse routing.
● // route declaration
● Route::get(‘login’, ‘users@login’);
● Using reverse routing we can create a link to it and pass in any
parameters that we have defined. Optional parameters, if not
supplied, are removed from the generated link.
● {{ HTML::link_to_action('users@login') }}
● 0
● Q20.
● How to turn off CRSF protection for specific
route in Laravel?
● Posted by Sharad Jaiswal
● To turn off CRSF protection in Laravel add following codes in
“app/Http/Middleware/VerifyCsrfToken.php”
●
//add an array of Routes to skip CSRF check
private $exceptUrls = ['controller/route1',
'controller/route2'];
//modify this function
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);
}
● 0
● Q21.
● What are traits in Laravel?
● Posted by Sharad Jaiswal
● PHP Traits are simply a group of methods that you want include
within another class. A Trait, like an abstract class cannot be
instantiated by itself.Trait are created to reduce the limitations of
single inheritance in PHP by enabling a developer to reuse sets of
methods freely in several independent classes living in different
class hierarchies.
● Here is an example of trait.
● trait Sharable {
● You could then include this Trait within other classes like this:
●
class Post {
use Sharable;
}
class Comment {
use Sharable;
● Now if you were to create new objects out of these classes you
would find that they both have the share() method available:
●
$post = new Post;
echo $post->share(''); // 'share this item'
● 0
● Q22.
● Does Laravel support caching?
● Posted by Sharad Jaiswal
● Yes, Laravel supports popular caching backends like Memcached
and Redis.
● By default, Laravel is configured to use the file cache driver, which
stores the serialized, cached objects in the file system.For large
projects, it is recommended to use Memcached or Redis.
● 0
● Q23.
● Explain Laravel’s Middleware?
● Posted by Sharad Jaiswal
● As the name suggests, Middleware acts as a middleman between
request and response. It is a type of filtering mechanism. For
example, Laravel includes a middleware that verifies whether the
user of the application is authenticated or not. If the user is
authenticated, he will be redirected to the home page otherwise,
he will be redirected to the login page.
● There are two types of Middleware in Laravel.
● Global Middleware: will run on every HTTP request of the
application.
● Route Middleware: will be assigned to a specific route.
● Read more about Laravel middlewares
● 0
● Q24.
● What is Lumen?
● Posted by Sharad Jaiswal
● Lumen is PHP micro-framework that built on Laravel’s top
components.It is created by Taylor Otwell. It is perfect option for
building Laravel based micro-services and fast REST API’s. It’s one
of the fastest micro-frameworks available.
● You can install Lumen using composer by running below
command
● composer create-project --prefer-dist laravel/lumen blog
● 0
● Q25.
● Explain Bundles in Laravel?
● Posted by Sharad Jaiswal
● In Laravel, bundles are also called packages.Packages are the
primary way to extend the functionality of Laravel. Packages
might be anything from a great way to work with dates like
Carbon, or an entire BDD testing framework like Behat.In Laravel,
you can create your custom packages too.You can read more
about packages from here
● 0
● Q26.
● How to use custom table in Laravel Modal ?
● Posted by Sharad Jaiswal
● You can use custom table in Laravel by overriding protected
$table property of Eloquent.
●
Below is sample uses
}
● 0
● Q27.
● List types of relationships available in Laravel
Eloquent?
● Posted by Sharad Jaiswal
● Below are types of relationships supported by Laravel Eloquent
ORM.
○ One To One
○ One To Many
○ One To Many (Inverse)
○ Many To Many
○ Has Many Through
○ Polymorphic Relations
○ Many To Many Polymorphic Relations
● You can read more about relationships in Laravel Eloquent from
here
● 0
● Q28.
● Why are migrations necessary?
● Posted by Sharad Jaiswal
● Migrations are necessary because:
○ Without migrations, database consistency when sharing
an app is almost impossible, especially as more and more
people collaborate on the web app.
○ Your production database needs to be synced as well.
● 0
● Q29.
● Provide System requirements for installation of
Laravel 5.4 ?
● Posted by Sharad Jaiswal
● In order to install laravel,make sure your server meets the
following requirements:
○ PHP >= 5.6.4
○ OpenSSL PHP Extension
○ PDO PHP Extension
○ Mbstring PHP Extension
○ Tokenizer PHP Extension
○ XML PHP Extension
● 0
● Q30.
● List some Aggregates methods provided by
query builder in Laravel ?
● Posted by Sharad Jaiswal
○ count()
○ max()
○ min()
○ avg()
○ sum()
1) What is the Laravel?
8) What is Binding?
A) Within a service provider, we always have access to the container via the
$this->app property. We can register a binding using the bind method,
passing the class or interface name that we wish to register along with a
Closure that returns an instance of the class:
});
A) The singleton method binds a class or interface into the container that
should only be resolved one time. Once a singleton binding is resolved, the
same object instance will be returned on subsequent calls into the container.
$this->app->instance(‘HelpSpot\API’, $api);
A) Sometimes you may have a class that receives some injected classes, but
also needs an injected primitive value such as an integer. You may easily use
contextual binding to inject any value your class may need:
$this->app->when(‘App\Http\Controllers\UserController’)
->needs(‘$variableName’)
->give($value);
A) Sometimes you may have two classes that utilize the same interface, but
you wish to inject different implementations into each class. For example,
two controllers may depend on different implementations of the
Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a
simple, fluent interface for defining this behavior:
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘local’);
});
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘s3’);
});
$this->app->bind(‘SpeedReport’, function () {
//
});
$this->app->bind(‘MemoryReport’, function () {
//
});
Once the services have been tagged, you may easily resolve them all via the
tagged method:
});
$this->app->extend(Service::class, function($service) {
});
A) You may use the make method to resolve a class instance out of the
container. The make method accepts the name of the class or interface you
wish to resolve:
$api = $this->app->make(‘HelpSpot\API’);
Laravel Interview Questions # 16) What are service providers?
A) within the register method, you should only bind things into the service
container. You should never attempt to register any event listeners, routes,
or any other piece of functionality within the register method.
A) If your service provider registers many simple bindings, you may wish to
use the bindings and singletons properties instead of manually registering
each container binding. When the service provider is loaded by the
framework, it will automatically check for these properties and register
their bindings
‘providers’ => [
App\Providers\ComposerServiceProvider::class,
],
A) Facades have many benefits. They provide a terse, memorable syntax that
allows you to use Laravel’s features without remembering long class names
that must be injected or configured manually. Furthermore, because of their
unique usage of PHP’s dynamic methods, they are easy to test.
A) Laravel’s Contracts are a set of interfaces that define the core services
provided by the framework. For example, a
Illuminate\Contracts\Queue\Queue contract defines the methods needed for
queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines
the methods needed for sending e-mail.
Unlike facades, which do not require you to require them in your class’
constructor, contracts allow you to define explicit dependencies for your
classes. Some developers prefer to explicitly define their dependencies in
this way and therefore prefer to use contracts, while other developers enjoy
the convenience of facades.
A) The most basic Laravel routes accept a URI and a Closure, providing a
very simple and expressive method of defining routes:
Route::get(‘foo’, function () {
});
Laravel Interview Questions # 30) Where do you locate Route files?
A) All Laravel routes are defined in your route files, which are located in the
routes directory.
Laravel Interview Questions # 31) What are the available Router Methods?
A) The router allows you to register routes that respond to any HTTP verb:
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
A) Any HTML forms pointing to POST, PUT, or DELETE routes that are
defined in the web routes file should include a CSRF token field. Otherwise,
the request will be rejected.
…
</form>
A) If you are defining a route that redirects to another URI, you may use the
Route::redirect method.
A) If your route only needs to return a view, you may use the Route:: view
method. The view method accepts a URI as its first argument and a view
name as its second argument. In addition, you may provide an array of data
to pass to the view as an optional third argument.
Route::view(‘/welcome’, ‘welcome’);
Route::get(‘user/profile’, function () {
//
})->name(‘profile’);
Route::middleware(‘auth:api’, ‘throttle:60,1’)->group(function () {
Route::get(‘/user’, function () {
//
});
});
A) Sometimes you may want to group several middleware under a single key
to make them easier to assign to routes. You may do this using the
$middlewareGroups property of your HTTP kernel.
A) Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is
included with each response generated by the framework. You can use the
cookie value to set the X-XSRF-TOKEN request header.
A) All routes and controllers should return a response to be sent back to the
user’s browser. Laravel provides several different ways to return responses.
The most basic response is returning a string from a route or controller. The
framework will automatically convert the string into a full HTTP response:
Route::get(‘/’, function () {
return ‘Hello World’;
});
Route::get(‘dashboard’, function () {
return redirect(‘home/dashboard’);
});
A) If you would like to define a custom response that you can re-use in a
variety of your routes and controllers, you may use the macro method on
the Response facade.
A) Views contain the HTML served by your application and separate your
controller / application logic from your presentation logic. Views are stored
in the resources/views directory. A simple view might look something like
this:
<html>
<body>
</html>
A) View composers are callbacks or class methods that are called when a
view is rendered. If you have data that you want to be bound to a view each
time that view is rendered, a view composer can help you organize that logic
into a single location.
A) View creators are very similar to view composers; however, they are
executed immediately after the view is instantiated instead of waiting until
the view is about to render. To register a view creator, use the creator
method:
View::creator(‘profile’, ‘App\Http\ViewCreators\ProfileCreator’);
A) Laravel provides several helpers to assist you in generating URLs for your
application. Of course, these are mainly helpful when building links in your
templates and API responses, or when generating redirect responses to
another part of your application.
51) What is u
rl helper?
A) The url helper may be used to generate arbitrary URLs for your
application. The generated URL will automatically use the scheme (HTTP or
HTTPS) and host from the current request:
$post = App\Post::find(1);
echo url(“/posts/{$post->id}”);
// http://example.com/posts/1
A) The render methos is responsible for converting a given exception into an
HTTP response that should be sent back to the browser. By default, the
exception is passed to the base class which generates a response for you.
A) Some exceptions describe HTTP error codes from the server. For
example, this may be a “page not found” error (404), an “unauthorized
error” (401) or even a developer generated 500 error.
A) Laravel utilizes the Monolog library, which provides support for a variety
of powerful log handlers. Laravel makes it a cinch to configure these
handlers, allowing you to mix and match them to customize your
application’s log handling.
A) By default, Laravel will use the stack channel when logging messages.
The stack channel is used to aggregate multiple log channels into a single
channel.
58) What are Blade Templates?
The Laravel query builder uses PDO parameter binding to protect your
application against SQL injection attacks. There is no need to clean strings
being passed as bindings.
MySQL
PostgreSQL
SQLite
SQL Server
A) When building JSON APIs, you will often need to convert your models and
relationships to arrays or JSON. Eloquent includes convenient methods for
making these conversions, as well as controlling which attributes are
included in your serializations.
$user = App\User::with(‘roles’)->first();
return $user->toArray();
$users = App\User::all();
Serializing To JSON – To convert a model to JSON, you should use the toJson
method. Like toArray, the toJson method is recursive, so all attributes and
relations will be converted to JSON:
$user = App\User::find(1);
return $user->toJson();
return $users->toArray();
1. What is Laravel
Laravel is free open source “PHP framework” based on MVC Design Pattern.
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in
creating a wonderful web application easily and quickly.
Read More
3. What is Lumen?
Lumen is PHP micro framework that built on Laravel’s top components. It is created by Taylor
Otwell.
It is the perfect option for building Laravel based micro-services and fast REST API’s.
6. What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.
It allows you to declare the libraries your project depends on and it will manage (install/update)
them for you.
It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel
over and over, we can instead download popular packages.
Use php artisan –version command to check current installed version of Laravel Framework
Usage:
● count()
● Usage:$products = DB::table(‘products’)->count();
● max()
● Usage:$price = DB::table(‘orders’)->max(‘price’);
● min()
● Usage:$price = DB::table(‘orders’)->min(‘price’);
● avg()
● Usage:$price = DB::table(‘orders’)->avg(‘price’);
● sum()
● Usage: $price = DB::table(‘orders’)->sum(‘price’);
if ($request->is($route)) {
return $next($request);
}
return parent::handle($request, $next);}
Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular
PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In
fact, all Blade views are compiled into plain PHP code and cached until they are modified,
meaning Blade adds essentially zero overhead to your application. Blade view files use the
.blade.php file extension and are typically stored in the resources/views directory.
Laravel Migrations are like version control for your database, allowing a team to easily modify
and share the application’s database schema. Migrations are typically paired with Laravel’s
schema builder to easily build your application’s database schema.
● Open to config/app.php
● Find ‘providers’ array of the various ServiceProviders.
● Add namespace ‘Iluminate\Abc\ABCServiceProvider:: class,’ to the end of the array.
Usage :
Route::controller('base URI','');
Composer re-reads the composer.json file to build up the list of files to autoload.
It is a powerful tool for resolving class dependencies and performing dependency injection in
Laravel.
Dependency injection is a fancy phrase that essentially means class dependencies are “injected”
into the class via the constructor or, in some cases, “setter” methods.
Usage:
DB::connection()->enableQueryLog();
You can get an array of the executed queries by using the getQueryLog method:
$queries = DB::getQueryLog();
Laravel self ships with many facades which provide access to almost all features of Laravel’s.
Laravel Facades serve as “static proxies” to underlying classes in the service container and
provides benefits of a terse, expressive syntax while maintaining more testability and flexibility
than traditional static methods of classes. All of Laravel’s facades are defined in the
IlluminateSupportFacades namespace. You can easily access a Facade like so:
use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('key');
});
Example Usage
foreach (Product::where('name', 'bar')->cursor() as $flight) {
You can read about How to Laravel contracts by How to use Laravel facade
PHP compact function takes each key and tries to find a variable with that same name.If the
variable is found, them it builds an associative array.
Usage:-
if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}
You can specify named routes by chaining the name method onto the route definition:
Route::get('user/profile', function () {
//
})->name('profile');
Route::get('user/profile', 'UserController@showProfile')->name('profile');
Once you have assigned a name to your routes, you may use the route's name
when generating URLs or redirects via the global route function:
// Generating URLs...
$url = route('profile');
// Generating Redirects...
return redirect()->route('profile');
trait Sharable {
}
You could then include this Trait within other classes like this:
class Post {
use Sharable;
class Comment {
use Sharable;
}
Now if you were to create new objects out of these classes you would find
that they both have the share() method available:
$post = new Post;
echo $post->share(''); // 'share this item'
// creating Migration
php artisan make:migration create_users_table
In Eloquent each database table has the corresponding MODEL that is used to interact with table
and perform a database related operation on the table.
namespace App;
use Illuminate\Database\Eloquent\Model;
}
42. Can laravel be hacked ?
answers to this question is NO.Laravel application’s are 100% secure (depends what you mean
by “secure” as well), in terms of things you can do to prevent unwanted data/changes done
without the user knowing.
Larevl have inbuilt CSRF security, input validations and encrypted session/cookies etc. Also,
Laravel uses a high encryption level for securing Passwords.
With every update, there’s the possibility of new holes but you can keep up to date with Symfony
changes and security issues on their site.
$product->save();
Active Record style ORMs map an object to a database row. In the above example, we would be
mapping the Product object to a row in the products table of database.
● One To One
● One To Many
● One To Many (Inverse)
● Many To Many
● Has Many Through
● Polymorphic Relations
● Many To Many Polymorphic Relations
● MySQL
● Postgres
● SQLite
● SQL Server
$environment = App::environment();
dd($environment);
To generate the hidden input field _method, you may also use the method_field helper function:
<?php echo method_field('PUT'); ?>
{{ method_field('PUT') }}
Example
Route::get('/', function () {
//
})->middleware('firstMiddleware', 'secondMiddleware');
PHP QUESTIONS
● Question 11. Explain About Laravel Project?
● Answer :
○ 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.
● Question 12. What Are Advantages Of Laravel?
● Answer :
○ Easy and consistent syntax
○ Set-up process is easy
○ customization process is easy
○ code is always regimented with Laravel
● Question 13. What Is Laravel?
● Answer :
○ 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.
● Question 14. What Is System Requirement For Installation Of Laravel 5.2
(latest Version)?
● Answer :
○ PHP >= 5.5.9
○ OpenSSL PHP Extension
○ PDO PHP Extension
○ Mbstring PHP Extension
○ Tokenizer PHP Extension
● Question 15. How To Install Laravel?
● Answer :
● We can install the Laravel in following ways.
○ Laravel Installer
○ Composer Create-Project
● Question 16. Is Laravel An Open Source?
● Answer :
● Yes, Download the framework and use as per your requirement
● Question 17. What Is Offical Website Url Of Laravel?
● Answer :
● laravel.com.
● Question 18. In Which Language It Was Written?
● Answer :
● PHP.
● Question 19. What Is Current Stable Version Of Laravel?
● Answer :
● Version 5.2.36 dated June 6, 2016
● Question 20. When Laravel Was Launched?
● Answer :
● June 2011
● Question 21. What Developed The Laravel?
● Answer :
● Taylor Otwell.
● Question 22. What Are System Requirement For Laravel 5.0?
● Answer :
● Following are system requirements:
○ PHP >= 5.4, PHP < 7
○ Mcrypt PHP Extension
○ OpenSSL PHP Extension
○ Mbstring PHP Extension
○ Tokenizer PHP Extension
● Question 6. What Is The Difference Between $message And $$message?
● Answer :
● $message is a simple variable whereas $$message is a variable's
variable,which means
● value of the variable. Example:
● $user = 'bob'
● is equivalent to
● $message = 'user';
● $$message = 'bob';
● Question 7. What Is A Persistent Cookie?
● Answer :
● A persistent cookie is a cookie which is stored in a cookie file permanently
on the browser's computer. By default, cookies are created as temporary
cookies which stored only in the browser's memory. When the browser is
closed, temporary cookies will be erased. You should decide when to use
temporary cookies and when to use persistent cookies based on their
differences:
● · Temporary cookies can not be used for tracking long-term information.
● · Persistent cookies can be used for tracking long-term information.
● · Temporary cookies are safer because no programs other than the browser
can access them.
● · Persistent cookies are less secure because users can open cookie files see
the cookie values.
● Question 8. How Do You Define A Constant?
● Answer :
● Via define() directive, like define ("MYCONSTANT", 100);
● Question 9. What Are The Differences Between Require And Include,
Include_once?
● Answer :
● require_once() and include_once() are both the functions to include and
evaluate the specified file only once. If the specified file is included previous
to the present call occurrence, it will not be done again.
● But require() and include() will do it as many times they are asked to do.
● Question 10. What Is Meant By Urlencode And Urldecode?
● Answer :
● urlencode() returns the URL encoded version of the given string. URL coding
converts special characters into % signs followed by two hex digits. For
example: urlencode("10.00%") will return "10%2E00%25". URL encoded
strings are safe to be used as part of URLs.
● urldecode() returns the URL decoded version of the given string.
● Question 11. How To Get The Uploaded File Information In The Receiving
Script?
● Answer :
● Once the Web server received the uploaded file, it will call the PHP script
specified in the form action attribute to process them. This receiving PHP
script can get the uploaded file information through the predefined array
called $_FILES. Uploaded file information is organized in $_FILES as a
two-dimensional array as:
○ $_FILES[$fieldName]['name'] - The Original file name on the
browser system.
○ $_FILES[$fieldName]['type'] - The file type determined by the
browser.
○ $_FILES[$fieldName]['size'] - The Number of bytes of the file
content.
○ $_FILES[$fieldName]['tmp_name'] - The temporary filename of
the file in which
○ the uploaded file was stored on the server.
○ $_FILES[$fieldName]['error'] - The error code associated with
this file upload.
○ The $fieldName is the name used in the .
● Question 12. What Is The Difference Between Mysql_fetch_object And
Mysql_fetch_array?
● Answer :
● MySQL fetch object will collect first single matching record where
mysql_fetch_array will collect all matching records from the table in an
array.
● Question 13. How Can I Execute A Php Script Using Command Line?
● Answer :
● Just run the PHP CLI (Command Line Interface) program and provide the
PHP script file name as the command line argument. For example, "php
myScript.php", assuming "php" is the command to invoke the CLI program.
● Be aware that if your PHP script was written for the Web CGI interface, it
may not execute properly in command line environment.
● Question 14. I Am Trying To Assign A Variable The Value Of 0123, But It
Keeps Coming Up With A Different Number, What's The Problem?
● Answer :
● PHP Interpreter treats numbers beginning with 0 as octal. Look at the
similar PHP interview questions for more numeric problems.
● Question 15. Would I Use Print "$a Dollars" Or "{$a} Dollars" To Print Out
The Amount Of Dollars In This Example?
● Answer :
● In this example it wouldn’t matter, since the variable is all by itself, but if
you were to print something like "{$a},000,000 mln dollars", then you
definitely need to use the braces.
● Question 16. What Are The Different Tables Present In Mysql? Which
Type Of Table Is Generated When We Are Creating A Table In The
Following Syntax: Create Table Employee(eno Int(2),ename Varchar(10))?
● Answer :
● Total 5 types of tables we can create
● 1. MyISAM
● 2. Heap
● 3. Merge
● 4. INNO DB
● 5. ISAM
● MyISAM is the default storage engine as of MySQL 3.23. When you fire the
above
● create query MySQL will create a MyISAM table.
● Question 17. How To Create A Table?
● Answer :
● If you want to create a table, you can run the CREATE TABLE statement as
shown in the following sample script:
● <?php
include "mysql_connection.php";
$sql = "CREATE TABLE fyi_links ("
. " id INTEGER NOT NULL"
. ", url VARCHAR(80) NOT NULL"
. ", notes VARCHAR(1024)"
. ", counts INTEGER"
. ", time TIMESTAMP DEFAULT sysdate()"
. ")";
if (mysql_query($sql, $con)) {
print("Table fyi_links created.n");
} else {
print("Table creation failed.n");
}
mysql_close($con);
?>
● Example:
● setcookie('Test',$i,time()+3600);
● Test - cookie variable name
● $i - value of the variable 'Test'
● time()+3600 - denotes that the cookie will expire after an one hour.
● Question 119. How Can We Increase The Execution Time Of A Php Script?
● Answer :
● By the use of void set_time_limit(int seconds) Set the number of seconds a
script is allowed to run. If this is reached, the script returns a fatal error.
The default limit is 30 seconds or, if it exists, the max_execution_time
value defined in the php.ini. If seconds is set to zero, no time limit is
imposed.
● When called, set_time_limit() restarts the timeout counter from zero. In
other words, if the timeout is the default 30 seconds, and 25 seconds into
script execution a call such as set_time_limit(20) is made, the script will
run for a total of 45 seconds before timing out.
● Question 120. In How Many Ways We Can Retrieve Data In The Result Set
Of Mysql Using Php?
● Answer :
● mysql_fetch_array - Fetch a result row as an associative array, a numeric
array, or both.
● mysql_fetch_assoc - Fetch a result row as an associative array.
● mysql_fetch_object - Fetch a result row as an object.
● mysql_fetch_row —- Get a result row as an enumerated array.
● Question 121. Who Is The Father Of Php And What Is The Current Version
Of Php And Mysql?
● Answer :
● Rasmus Lerdorf.
● PHP 5.1. Beta
● MySQL 5.0
● Question 122. What's The Difference Between Include And Require?
● Answer :
● It’s how they handle failures. If the file is not found by require(), it will cause
a fatal error and halt the execution of the script. If the file is not found by
include(), a warning will be issued, but execution will continue.
● Question 123. Steps For The Payment Gateway Processing?
● Answer :
● An online payment gateway is the interface between your merchant
account and your Web site. The online payment gateway allows you to
immediately verify credit card transactions and authorize funds on a
customer’s credit card directly from your Web site. It then passes the
transaction off to your merchant bank for processing, commonly referred
to as transaction batching.
● Question 124. Can We Use Include(abc.php) Two Times In A Php Page
Makeit.php?
● Answer :
● Yes we can include that many times we want, but here are some things to
make sure of: (including abc.PHP, the file names are case-sensitive).
● there shouldn't be any duplicate function names, means there should not
be functions or classes or variables with the same name in abc.PHP and
makeit.php.
● Question 125. How Many Ways We Can Give The Output To A Browser?
● Answer :
● HTML output
● PHP, ASP, JSP, Servlet Function
● Script Language output Function
● Different Type of embedded Package to output to a browser.
● Question 126. What Are The Different Ways To Login To A Remote
Server? Explain The Means, Advantages And Disadvantages?
● Answer :
● There is at least 3 ways to logon to a remote server:
● Use ssh or telnet if you concern with security
● You can also use rlogin to logon to a remote server.
● Question 127. What Is Meant By Mime?
● Answer :
● MIME is Multipurpose Internet Mail Extensions is an Internet standard for
the format of e-mail. However browsers also uses MIME standard to
transmit files. MIME has a header which is added to a beginning of the
data. When browser sees such header it shows the data as it would be a
file (for example image) Some examples of MIME types:
● audio/x-ms-wmp
● image/png
● application/x-shockwave-flash
● Question 128. What Is The Difference Between Group By And Order By In
Sql?
● Answer :
● To sort a result, use an ORDER BY clause.
● The most general way to satisfy a GROUP BY clause is to scan the whole
table and create a new temporary table where all rows from each group are
consecutive, and then use this temporary table to discover groups and
apply aggregate functions (if any). ORDER BY [col1],[col2],...[coln]; Tells
DBMS according to what columns it should sort the result. If two rows will
have the same value in col1 it will try to sort them according to col2 and so
on.
● GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results
with same value of column col1. You can use COUNT(col1), SUM(col1),
AVG(col1) with it, if you want to count all items in group, sum all values or
view average.
● Question 129. Who Is The Father Of Php And Explain The Changes In Php
Versions?
● Answer :
● Rasmus Lerdorf is known as the father of PHP.PHP/F1 2.0 is an early and
no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0
and is a lot nicer. PHP 4 is the current generation of PHP, which uses the
Zend engine under the hood. PHP 5 uses Zend engine 2 which, among
other things, offers many additionalOOP features .
● Question 130. Which Method Do You Follow To Get A Record From A
Million Records? (searching Not From Database, From An Array In Php)?
● Answer :
● use array_searchfl, array_keys, arrayyalues, array_key_exists, and in_array.
● Question 131. Are Namespaces Are There In Javascript?
● Answer :
● A namespace is a container and allows you to bundle up all your
functionality using a unique name. In JavaScript, a namespace is really just
an object that you’ve attached all further methods, properties and objects.
But it is not always necessary to use namespace.
● Question 132. What Is 'float' Property In Css?
● Answer :
● The float property sets where an image or a text will appear in another
element.
● Question 133. What Are The Advantages/disadvantages Of Mysql And
Php?
● Answer :
● Both of them are open source software (so free of cost), support cross
platform. php is faster then ASP and iSP.
● Question 134. What Are The File Upload Settings In Configuration File?
● Answer :
● There are several settings in the PHP configuration file related to file
uploading:
● • file_uploads = On/Off - Whether or not to allow HTTP file uploads.
● • upload_tmp_dir = directory - The temporary directory used for storing files
when doing file upload.
● • upload_max_filesize = size - The maximum size of an uploaded file.
● Question 135. How To Uploaded Files To A Table?
● Answer :
● To store uploaded files to MySQL database, you can use the normal
SELECT statement as shown in the modified
processing_uploaded_files.php listed below:
● <?php
● $con = mysql_connect("localhost", "", "");
● mysql_select_db("pickzy");
● $error = $_FILES['pickzycenter_logo']['error'];
● $tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
● $size = $_FILES['pickzycenter_logo']['size'];
● $name = $_FILES['pickzycenter_logo']['name'];
● $type = $_FILES['pickzycenter_logo']['type'];
● print("
● \n");
● if ($error == UPLOAD_ERR_OK && $size > 0) {
● $fp = fopen($tmp_name, 'r');
● $content = fread($fp, $size);
● fclose($fp);
● $content = addslashes($content);
● $sql = "INSERT INTO pickzy_files (name, type, size, content)"
● . " VALUES ('$name', '$type', $size, '$content')";
● mysql_query($sql, $con);
● print("File stored.\n");
● } else {
● print("Upload faield.\n");
● }
● print("
● \n");
● mysql_close($con);
● ?>
● Note that addslashes() is used to add backslashes to special characters
that need to be protected in SQL statements.
● Question 136. How To Create A Table To Store Files?
● Answer :
● If you using MySQL database and want to store files in database, you need
to create BLOB columns, which can holds up to 65,535 characters. Here is
a sample script that creates a table with a BLOB column to be used to
store uploaded files:
● <?php
● $con = mysql_connect("localhost", "", "");
● mysql_select_db("pickzy");
● $sql = "CREATE TABLE pickzy_files ("
● . " id INTEGER NOT NULL AUTO_INCREMENT"
● . ", name VARCHAR(80) NOT NULL"
● . ", type VARCHAR(80) NOT NULL"
● . ", size INTEGER NOT NULL"
● . ", content BLOB"
● . ", PRIMARY KEY (id)"
● . ")";
● mysql_query($sql, $con);
● mysql_close($con);
● ?>
● Question 137. Why Do You Need To Filter Out Empty Files?
● Answer :
● When you are processing uploaded files, you need to check for empty files,
because they could be resulted from a bad upload process but the PHP
engine could still give no error.
● For example, if a user typed a bad file name in the upload field and
submitted the form, the PHP engine will take it as an empty file without
raising any error. The script below shows you an improved logic to process
uploaded files:
● <?php
● $file = '\pickzycenter\images\pickzycenter.logo';
● $error = $_FILES['pickzycenter_logo']['error'];
● $tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
● print("
● \n");
● if ($error==UPLOAD_ERR_OK) {
● if ($_FILES['pickzycenter_logo']['size'] > 0) {
● move_uploaded_file($tmp_name, $file);
● print("File uploaded.\n");
● } else {
● print("Loaded file is empty.\n");
● }
● } else if ($error==UPLOAD_ERR_NO_FILE) {
● print("No files specified.\n");
● } else {
● print("Upload faield.\n");
● }
● print("
● \n");
● ?>
● Question 138. How To Move Uploaded Files To Permanent Directory?
● Answer :
● PHP stores uploaded files in a temporary directory with temporary file
names. You must move uploaded files to a permanent directory, if you
want to keep them permanently.
● PHP offers the move_uploaded_file() to help you moving uploaded files.
The example script, processing_ uploaded_files.php, below shows a good
example:
● <?php
● $file = '\pickzycenter\images\pickzycenter.logo';
● print("<pre>\n");
● move_uploaded_file($_FILES['pickzycenter_logo']['tmp_name'], $file);
● print("File uploaded: ".$file."\n");
● print("</pre>\n");
● ?>
● Note that you need to change the permanent directory,
"\pickzycenter\images\", used in this script to something else on your Web
server. If your Web server is provided by a Web hosting company, you may
need to ask them which directories you can use to store files.
● If you copy both scripts, logo_upload.php and
processing_uploaded_files.php, to your Web server, you can try them to
upload an image file to your Web server.
● Question 139. How To Process The Uploaded Files?
● Answer :
● How to process the uploaded files? The answer is really depending on your
application. For example:
○ You can attached the outgoing emails, if the uploaded files are
email attachments.
○ You can move them to user's Web page directory, if the
uploaded files are user's Web pages.
○ You can move them to a permanent directory and save the
files names in the database, if the uploaded files are articles to
be published on the Web site.
○ You can store them to database tables, if you don't want store
them as files.
● Question 140. How Many Escape Sequences Are Recognized In
Single-quoted Strings?
● Answer :
● There are 2 escape sequences you can use in single-quoted strings:
● • \\ - Represents the back slash character.
● • \' - Represents the single quote character.
● Question 141. What Are The Special Characters You Need To Escape In
Double-quoted Stings?
● Answer :
● There are two special characters you need to escape in a double-quote
string: the double quote (") and the back slash (\). Here is a PHP script
example of double-quoted strings:
● <?php
● echo "Hello world!";
● echo "Tom said: \"Who's there?\"";
● echo "\\ represents an operator.";
● ?>
● This script will print:
● Hello world!Tom said: "Who's there?"\ represents an operator.
● Question 142. How Many Escape Sequences Are Recognized In
Double-quoted Strings?
● Answer :
● There are 12 escape sequences you can use in double-quoted strings:
● • \\ - Represents the back slash character.
● • \" - Represents the double quote character.
● • \$ - Represents the dollar sign.
● • \n - Represents the new line character (ASCII code 10).
● • \r - Represents the carriage return character (ASCII code 13).
● • \t - Represents the tab character (ASCII code 9).
● • \{ - Represents the open brace character.
● • \} - Represents the close brace character.
● • \[ - Represents the open bracket character.
● • \] - Represents the close bracket character.
● • \nnn - Represents a character as an octal value.
● • \xnn - Represents a character as a hex value.
● Question 143. How To Include Variables In Double-quoted Strings?
● Answer :
● Variables included in double-quoted strings will be interpolated. Their
values will be concatenated into the enclosing strings. For example, two
statements in the following PHP script will print out the same string:
● <?php
● $variable = "and";
● echo "part 1 $variable part 2\n";
● echo "part 1 ".$variable." part 2\n";
● ?>
● This script will print:
● part 1 and part 2
● part 1 and part 2
● Question 144. How To Access A Specific Character In A String?
● Answer :
● Any character in a string can be accessed by a special string element
expression:
● • $string{index} - The index is the position of the character counted from
left and starting from 0.
● Here is a PHP script example:
● <?php
● $string = 'It\'s Friday!';
● echo "The first character is $string{0}\n";
● echo "The first character is {$string{0}}\n";
● ?>
● This script will print:
● The first character is It's Friday!{0}
● The first character is I
● Question 145. How To Assigning A New Character In A String?
● Answer :
● The string element expression, $string{index}, can also be used at the left
side of an assignment statement. This allows you to assign a new
character to any position in a string. Here is a PHP script example:
● <?php
● $string = 'It\'s Friday?';
● echo "$string\n";
● $string{11} = '!';
● echo "$string\n";
● ?>
● This script will print:
● It's Friday?
● It's Friday!
● Question 146. How To Get The Number Of Characters In A String?
● Answer :
● You can use the "strlen()" function to get the number of characters in a
string. Here is a PHP script example of strlen():
● <?php
● print(strlen('It\'s Friday!'));
● ?>
● This script will print:
● 12
● Question 147. How To Remove The New Line Character From The End Of
A Text Line?
● Answer :
● If you are using fgets() to read a line from a text file, you may want to use
the chop() function to remove the new line character from the end of the
line as shown in this PHP script:
● <?php
● $handle = fopen("/tmp/inputfile.txt", "r");
● while ($line=fgets()) {
● $line = chop($line);
● # process $line here...
● }
● fclose($handle);
● ?>
● Question 148. How To Remove Leading And Trailing Spaces From User
Input Values?
● Answer :
● If you are taking input values from users with a Web form, users may enter
extra spaces at the beginning and/or the end of the input values. You
should always use the trim() function to remove those extra spaces as
shown in this PHP script:
● <?php
● $name = $_REQUEST("name");
● $name = trim($name);
● # $name is ready to be used...
● ?>
● Question 149. How To Take A Substring From A Given String?
● Answer :
● If you know the position of a substring in a given string, you can take the
substring out by the substr() function. Here is a PHP script on how to use
substr():
● <?php
● $string = "beginning";
● print("Position counted from left: ".substr($string,0,5)."\n");
● print("Position counted form right: ".substr($string,-7,3)."\n");
● ?>
● This script will print:
● Position counted from left: begin
● Position counted form right: gin
● substr() can take negative starting position counted from the end of the
string.
● Question 150. How To Replace A Substring In A Given String?
● Answer :
● If you know the position of a substring in a given string, you can replace
that substring by another string by using the substr_replace() function.
Here is a PHP script on how to use substr_replace():
● <?php
● $string = "Warning: System will shutdown in NN minutes!";
● $pos = strpos($string, "NN");
● print(substr_replace($string, "15", $pos, 2)."\n");
● sleep(10*60);
● print(substr_replace($string, "5", $pos, 2)."\n");
● ?>
● This script will print:
● Warning: System will shutdown in 15 minutes!
● (10 minutes later)
● Warning: System will shutdown in 5 minutes!
● Like substr(), substr_replace() can take negative starting position counted
from the end of the string.
● Question 151. How To Convert Strings To Upper Or Lower Cases?
● Answer :
● Converting strings to upper or lower cases are easy. Just use strtoupper()
or strtolower() functions. Here is a PHP script on how to use them:
● <?php
● $string = "PHP string functions are easy to use.";
● $lower = strtolower($string);
● $upper = strtoupper($string);
● print("$lower\n");
● print("$upper\n");
● print("\n");
● ?>
● This script will print:
● php string functions are easy to use.
● PHP STRING FUNCTIONS ARE EASY TO USE.
● Question 152. How To Convert The First Character To Upper Case?
● Answer :
● If you are processing an article, you may want to capitalize the first
character of a sentence by using the ucfirst() function. You may also want
to capitalize the first character of every words for the article title by using
the ucwords() function. Here is a PHP script on how to use ucfirst() and
ucwords():
● <?php
● $string = "php string functions are easy to use.";
● $sentence = ucfirst($string);
● $title = ucwords($string);
● print("$sentence\n");
● print("$title\n");
● print("\n");
● ?>
● This script will print:
● Php string functions are easy to use.
● Php String Functions Are Easy To Use.
● Question 153. How To Convert Strings In Hex Format?
● Answer :
● If you want convert a string into hex format, you can use the bin2hex()
function. Here is a PHP script on how to use bin2hex():
● <?php
● $string = "Hello\tworld!\n";
● print($string."\n");
● print(bin2hex($string)."\n");
● ?>
● This script will print:
● Hello world!
● 48656c6c6f09776f726c64210a
● Question 154. How To Generate A Character From An Ascii Value?
● Answer :
● If you want to generate characters from ASCII values, you can use the chr()
function.
● chr() takes the ASCII value in decimal format and returns the character
represented by the ASCII value. chr() complements ord(). Here is a PHP
script on how to use chr():
● <?php
● print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n");
● print(ord("H")."\n");
● ?>
● This script will print:
● Hello
● 72
● Question 155. How To Convert A Character To An Ascii Value?
● Answer :
● If you want to convert characters to ASCII values, you can use the ord()
function, which takes the first charcter of the specified string, and returns
its ASCII value in decimal format. ord() complements chr(). Here is a PHP
script on how to use ord():
● <?php
● print(ord("Hello")."\n");
● print(chr(72)."\n");
● ?>
● This script will print:
● 72
● H
● Question 156. How To Join Multiple Strings Into A Single String?
● Answer :
● If you multiple strings stored in an array, you can join them together into a
single string with a given delimiter by using the implode() function. Here is
a PHP script on how to use implode():
● <?php
● $date = array('01', '01', '2006');
● $keys = array('php', 'string', 'function');
● print("A formated date: ".implode("/",$date)."\n");
● print("A keyword list: ".implode(", ",$keys)."\n");
● ?>
● This script will print:
● A formated date: 01/01/2006
● A keyword list: php, string, function
● Question 157. What Is An Array In Php?
● Answer :
● An array in PHP is really an ordered map of pairs of keys and values.
● Comparing with Perl, an array in PHP is not like a normal array in Perl. An
array in PHP is like an associate array in Perl. But an array in PHP can work
like a normal array in Perl.
● Comparing with Java, an array in PHP is not like an array in Java. An array
in PHP is like a TreeMap class in Java. But an array in PHP can work like
an array in Java.
● Question 158. How To Test If A Variable Is An Array?
● Answer :
● Testing if a variable is an array is easy. Just use the is_array() function.
Here is a PHP script on how to use is_array():
● <?php
● $var = array(0,0,7);
● print("Test 1: ". is_array($var)."\n");
● $var = array();
● print("Test 2: ". is_array($var)."\n");
● $var = 1800;
● print("Test 3: ". is_array($var)."\n");
● $var = true;
● print("Test 4: ". is_array($var)."\n");
● $var = null;
● print("Test 5: ". is_array($var)."\n");
● $var = "PHP";
● print("Test 6: ". is_array($var)."\n");
● print("\n");
● ?>
● This script will print:
● Test 1: 1
● Test 2: 1
● Test 3:
● Test 4:
● Test 5:
● Test 6:
● Question 159. How To Retrieve Values Out Of An Array?
● Answer :
● You can retrieve values out of arrays using the array element expression
$array[$key].
● Here is a PHP example script:
● <?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"]
= "Perl";
● $languages["Two"] = "Java"; print("Array with inserted values:\n");
● print_r($languages); ?>
● This script will print:
● Array with default keys:
● The second value: Perl
● Array with specified keys:
● The third value: Java
● Question 160. How Values In Arrays Are Indexed?
● Answer :
● Values in an array are all indexed their corresponding keys. Because we
can use either an integer or a string as a key in an array, we can divide
arrays into 3 categories:
○ Numerical Array - All keys are sequential integers.
○ Associative Array - All keys are strings.
○ Mixed Array - Some keys are integers, some keys are strings.
● Question 161. How The Values Are Ordered In An Array?
● Answer :
● PHP says that an array is an ordered map. But how the values are ordered
in an array?
● The answer is simple. Values are stored in the same order as they are
inserted like a queue. If you want to reorder them differently, you need to
use a sort function. Here is a PHP script show you the order of array
values:
● <?php
● $mixed = array();
● $mixed["Two"] = "Java";
● $mixed["3"] = "C+";
● $mixed["Zero"] = "PHP";
● $mixed[1] = "Perl";
● $mixed[""] = "Basic";
● $mixed[] = "Pascal";
● $mixed[] = "FORTRAN";
● $mixed["Two"] = "";
● unset($mixed[4]);
● print("Order of array values:\n");
● print_r($mixed);
● ?>
● This script will print:
● Order of array values:
● Array
● (
● [Two] =>
● [3] => C+
● [Zero] => PHP
● [1] => Perl
● [] => Basic
● [5] => FORTRAN
● )
● Question 162. How To Get The Total Number Of Values In An Array?
● Answer :
● You can get the total number of values in an array by using the count()
function. Here is a PHP example script:
● <?php
● $array = array("PHP", "Perl", "Java");
● print_r("Size 1: ".count($array)."\n");
● $array = array();
● print_r("Size 2: ".count($array)."\n");
● ?>
● This script will print:
● Size 1: 3
● Size 2: 0
● Note that count() has an alias called sizeof().
● Question 163. How To Find A Specific Value In An Array?
● Answer :
● There are two functions can be used to test if a value is defined in an array
or not:
○ array_search($value, $array) - Returns the first key of the
matching value in the array, if found. Otherwise, it returns
false.
○ in_array($value, $array) - Returns true if the $value is defined in
$array.
● Here is a PHP script on how to use arrary_search():
● <?php
$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."n");
print("Search 2: ".array_search("Perl",$array)."n");
print("Search 3: ".array_search("C#",$array)."n");
print("n");
?>