Tags
PHP
Asked 7 years ago
5 Oct 2016
Views 498
jabber

jabber posted

foreach passing refrence in php

i want to change the

$products=array("Iphone","Samsung Galaxy","Google Pixel"); 
 
foreach($products as $key=>$value)
{
      $value=  $key."-".$value
}
print_r($products);

i want result like 1-iphone etc.. but it print as it is same array.
not changing the value if we change in foreach

i dont know i clearly explain my problem or not . let me know if need more detail
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

if you want to change the array in foreach by changing the $value at above code it should be pass by reference

so foreach($product as $key=>&$value)

here &$value means its not passing value of the array but passing associated refrence

so need code will be like


$products=array("Iphone","Samsung Galaxy","Google Pixel"); 
 
foreach($products as $key=>&$value)
{
      $value=  $key."-".$value
}
print_r($products);



result will be
Array("1-Iphone","2-Samsung Galaxy","3-Google Pixel")
Mahesh Radadiya

Mahesh Radadiya
answered Nov 30 '-1 00:00


$products=array("Iphone","Samsung Galaxy","Google Pixel"); 

foreach($products as $key=>&$value)
{
      $products[$key]=  $key."-".$value;
}
print_r($products);



use direct array name with index and you can change value direct in loop
result

Array ( [0] => 0-Iphone [1] => 1-Samsung Galaxy [2] => 2-Google Pixel ) 


Post Answer