pass by value and pass by reference in php – Pass by value vs. pass by reference

pass by value and pass by reference in php – only values of actual parameters are passing to the function. Function pass by value vs. pass by reference. PHP allows you to call function by value and reference both.

Pass by Value and Pass by Reference Example in PHP

You can pass a variable by reference to a function so the function can modify the variable. pass by value and pass by reference in php By default, PHP variables are passed by value as the function arguments in PHP.

Read Also:  Fix: file_get_contents() wrapper is disabled error in PHP

Example: Pass by Value in PHP

pass by value and pass by reference in php

function print_string( $user_input ) { 
    $user_input = "I am Jalpa!"; 
    print($user_input); 
} 
  
$user_input = "I am mayur dhameliya";
print_string($user_input); 
print($user_input); 

Result

I am Jalpa
I am mayur dhameliya

Pass by reference in PHP:

Example

function print_string( &$user_input ) { 
    $user_input = "I am Jalpa!"; 
    print($user_input); 
} 
  
$user_input = "I am mayur dhameliya";
print_string($user_input); 
print($user_input);

Result

I am Jalpa
I am Jalpa

Don’t miss: Php Function Default Value

What is Pass By Reference and Pass By Value in PHP?

Example

<?php
   function rankdyanmic(&$arg){
      $arg++;
   }
   $arg=5;
   rankdyanmic($arg);
   echo $arg;
?>

Result

6

pass by value

<?php
   function rankdyanmic($arg){
      $arg++;
   echo $arg."<br/>";
   }
   $arg=5;
   rankdyanmic($arg);
   echo $arg;
?>

Result
6
5

I hope you get an idea about pass by value and pass by reference in php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.