php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #37761 Pass by reference function parameter passed as copy
Submitted: 2006-06-09 11:17 UTC Modified: 2006-06-09 13:01 UTC
From: hadrianoliver at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5CVS-2006-06-09 (snap) OS: Windows XP Service Pack 2
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: hadrianoliver at hotmail dot com
New email:
PHP Version: OS:

 

 [2006-06-09 11:17 UTC] hadrianoliver at hotmail dot com
Description:
------------
When passing an argument to a function such as: -

  preg_match( string pattern, string subject [, array &matches [, int flags [, int offset]]] )

using the syntax:

  preg_match($pattern, $subject, $array = array())

a copy of the $array is passed to the function, rather than a pointer.

Reproduce code:
---------------
// Without first defining variable
preg_match("/a/", "a", $matches1);
echo count($matches1); // Outputs 1 - OK

// Defining variable before function call
$matches2 = array();
preg_match("/a/", "a", $matches2);
echo count($matches2); // Outputs 1 - OK

// Defining variable within function parameters
preg_match("/a/", "a", $matches3 = array());
echo count($matches3); // Outputs 0 - UNEXPECTED!!



Expected result:
----------------
Expected result: 111


Actual result:
--------------
Observed result: 110

Further toying around, such as by using: -

function _array() 
{
  $a = array('a', 'b', 'c');
}

instead of array() and 

function _preg_match($pattern, $subject, &$matches)
{
  if (!$matches) 
  {
    $digits = array();
  }
  echo "in: " . count($matches) ."<br/>\n";
  $result = preg_match($pattern, $subject, $matches);
  echo "out: " . count($matches) ."<br/>\n";
  return $result;
}

instead of preg_match(), reveal that the array is being passed by copy, not reference.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-06-09 11:19 UTC] hadrianoliver at hotmail dot com
//Correction: _array() function should be:

function &_array() 
{
  $a = array('a', 'b', 'c');
  return $a;
}
 [2006-06-09 13:01 UTC] mike@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

http://php.net/manual/en/language.references.pass.php
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC