SlideShare a Scribd company logo
1 of 1
Download to read offline
www.InnovativePhp.com
Parameter Passing Techniques in CodeIgniter
2010-10-10 03:10:08 nimeshrmr

I have been using code Igniter framework in my recent projects. Recently one of my friends ran into a
problem when passing optional parameters to controller function. So i decided to write this article to share
the knowledge i gained by solving that problem.

Lets start by using a simple example.

1. Accessing paramets as pre defined varibles in controller function

Ex : http://www.yoursite.com/index.php/Student/Create/Mark/22

class Student extends Controller{
public function __construct() { parent::Controller();
  } public function create($name,$age){
     $studentName = $name;  $studentAge = $age;
   }
}

When you call a controller function in code igniter the first two parameters after index.php is Controller
Class name and Controller class function respectively. In this method there are two other parameters
separated by ‘/’ . These two components are the two get parameters passes to the functiion. We can
access these get parameters by using two variables as shown in the example.



Name in the create function would be the first parameter in the url after create. So value of $name will be
Mark.
Age in the create function would be the second parameter in the url after create . So value of $age will be
22.

2. Accessing parameters without defining variables in controller function

Ex : http://www.yoursite.com/index.php/Student/Create/Mark/22
class Student extends Controller{
    public function __construct() {
        parent::Controller();
    }
    public function create(){
        $studentName = $this->uri->segment(3);
        $studentAge = $this->uri->segment(4);
    }
}

This method can be used to get parameters passed to a controller function without defining variables
statically in the function declaration. In code igniter url parameters can be accessed by using the uri-
>segment function.
 $this->uri->segment(param no);                // You can use $this when using inside the controller function. Parameter number is required.

The first two segments of the url will always be Controller Class and Controller Function in
CodeIgniter. So if you want to access parameters , you have to start from index 3. In the above example
we can access the two parameters using index 3 and 4. This method is useful when the number of
parameters are dynamic.

3. Accessing Parameters Using Key Value Pairs

Ex : http://www.yoursite.com/index.php/Student/Create/Name/Mark/Age/22
<?php
class Student extends Controller{
    public function __construct() {
        parent::Controller();
    }
    public function create(){
        $parameters = $this->uri->uri_to_assoc();
        $studentName = $parameters['Name'];
        $studentAge = $parameters['Age'];
    }
}
?>

Consider a situation where the number of parameters passed to a function are dynamic and some of the
parameters are optional. Example is given below.

http://www.yoursite.com/index.php/Student/Create/Mark

http://www.yoursite.com/index.php/Student/Create/Mark/22



In previos two urls the age is optionnal. so we dont pass it every time we use the function . Hence it is
difficult to access the optional parameter through predefined varibales or url indexes.

In these type of situations you cannot use the first method and also the second method is very hard to
use. We can access parameters with key-value pairs to solve this problem. CodeIgniter provides a
method called uri->uri_to_assoc();

So in the url provided in the previos example (Name/Mark/Age/22) will be broken into 2keys and 2 values.
Name and Age will be the two keys and Mark and 22 will be the values for those keys respectiively. I prefer
this methos since ii know exactly what are the parameters i am accessing.

Hope you enjoyed the post on Parameter Passing Techniques in CodeIgniter. Please feel free to
comment with your sugesstions and content of this post.

More Related Content

What's hot

Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
LEDC 2016
 

What's hot (20)

07 Php Mysql Update Delete
07 Php Mysql Update Delete07 Php Mysql Update Delete
07 Php Mysql Update Delete
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
06 Php Mysql Connect Query
06 Php Mysql Connect Query06 Php Mysql Connect Query
06 Php Mysql Connect Query
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話
 
Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018
 
22.sessions in laravel
22.sessions in laravel22.sessions in laravel
22.sessions in laravel
 
REST API with CakePHP
REST API with CakePHPREST API with CakePHP
REST API with CakePHP
 
[Srijan Wednesday Webinars] Routing in Drupal 8: Decoupling hook_menu
[Srijan Wednesday Webinars] Routing in Drupal 8: Decoupling hook_menu[Srijan Wednesday Webinars] Routing in Drupal 8: Decoupling hook_menu
[Srijan Wednesday Webinars] Routing in Drupal 8: Decoupling hook_menu
 
Elixir flow: Building and tuning concurrent workflows
Elixir flow: Building and tuning concurrent workflowsElixir flow: Building and tuning concurrent workflows
Elixir flow: Building and tuning concurrent workflows
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015
 
Php if
Php ifPhp if
Php if
 
System performance tuning
System performance tuningSystem performance tuning
System performance tuning
 
6. hello popescu 2
6. hello popescu 26. hello popescu 2
6. hello popescu 2
 
Feeds drupal cafe
Feeds drupal cafeFeeds drupal cafe
Feeds drupal cafe
 
Owasp & php
Owasp & phpOwasp & php
Owasp & php
 
7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!
 

Similar to Code igniter parameter passing techniques

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
Core Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class DesignCore Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class Design
WebStackAcademy
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Application package
Application packageApplication package
Application package
JAYAARC
 
Poject documentation deepak
Poject documentation deepakPoject documentation deepak
Poject documentation deepak
chetankane
 
Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2
Wildan Maulana
 

Similar to Code igniter parameter passing techniques (20)

Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Object Oriented Programming (Advanced )
Object Oriented Programming   (Advanced )Object Oriented Programming   (Advanced )
Object Oriented Programming (Advanced )
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Core Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class DesignCore Java Programming Language (JSE) : Chapter VI - Class Design
Core Java Programming Language (JSE) : Chapter VI - Class Design
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
WordPress Hooks Action & Filters
WordPress Hooks Action & FiltersWordPress Hooks Action & Filters
WordPress Hooks Action & Filters
 
Application package
Application packageApplication package
Application package
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Poject documentation deepak
Poject documentation deepakPoject documentation deepak
Poject documentation deepak
 
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In  JavaMethod, Constructor, Method Overloading, Method Overriding, Inheritance In  Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
 
Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentation
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Code igniter parameter passing techniques

  • 1. www.InnovativePhp.com Parameter Passing Techniques in CodeIgniter 2010-10-10 03:10:08 nimeshrmr I have been using code Igniter framework in my recent projects. Recently one of my friends ran into a problem when passing optional parameters to controller function. So i decided to write this article to share the knowledge i gained by solving that problem. Lets start by using a simple example. 1. Accessing paramets as pre defined varibles in controller function Ex : http://www.yoursite.com/index.php/Student/Create/Mark/22 class Student extends Controller{ public function __construct() { parent::Controller(); } public function create($name,$age){ $studentName = $name; $studentAge = $age; } } When you call a controller function in code igniter the first two parameters after index.php is Controller Class name and Controller class function respectively. In this method there are two other parameters separated by ‘/’ . These two components are the two get parameters passes to the functiion. We can access these get parameters by using two variables as shown in the example. Name in the create function would be the first parameter in the url after create. So value of $name will be Mark. Age in the create function would be the second parameter in the url after create . So value of $age will be 22. 2. Accessing parameters without defining variables in controller function Ex : http://www.yoursite.com/index.php/Student/Create/Mark/22 class Student extends Controller{ public function __construct() { parent::Controller(); } public function create(){ $studentName = $this->uri->segment(3); $studentAge = $this->uri->segment(4); } } This method can be used to get parameters passed to a controller function without defining variables statically in the function declaration. In code igniter url parameters can be accessed by using the uri- >segment function. $this->uri->segment(param no); // You can use $this when using inside the controller function. Parameter number is required. The first two segments of the url will always be Controller Class and Controller Function in CodeIgniter. So if you want to access parameters , you have to start from index 3. In the above example we can access the two parameters using index 3 and 4. This method is useful when the number of parameters are dynamic. 3. Accessing Parameters Using Key Value Pairs Ex : http://www.yoursite.com/index.php/Student/Create/Name/Mark/Age/22 <?php class Student extends Controller{ public function __construct() { parent::Controller(); } public function create(){ $parameters = $this->uri->uri_to_assoc(); $studentName = $parameters['Name']; $studentAge = $parameters['Age']; } } ?> Consider a situation where the number of parameters passed to a function are dynamic and some of the parameters are optional. Example is given below. http://www.yoursite.com/index.php/Student/Create/Mark http://www.yoursite.com/index.php/Student/Create/Mark/22 In previos two urls the age is optionnal. so we dont pass it every time we use the function . Hence it is difficult to access the optional parameter through predefined varibales or url indexes. In these type of situations you cannot use the first method and also the second method is very hard to use. We can access parameters with key-value pairs to solve this problem. CodeIgniter provides a method called uri->uri_to_assoc(); So in the url provided in the previos example (Name/Mark/Age/22) will be broken into 2keys and 2 values. Name and Age will be the two keys and Mark and 22 will be the values for those keys respectiively. I prefer this methos since ii know exactly what are the parameters i am accessing. Hope you enjoyed the post on Parameter Passing Techniques in CodeIgniter. Please feel free to comment with your sugesstions and content of this post.