Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP pass array element by reference

I have two arrays, one indexed and one associative. What my question boils down to is, how can I pass the associative array's reference to the edit class. This way when there are more books and movies, I can loop through, clean all the isbn's and not touch movie. The problem I'm having is passing the reference inside the for loop.

$i = new intro();

class intro{
  public function __construct(){
    $index = array(array("book", "regex"), array("movie", "regex"));
    $assoc = array(array("book"=>"freeBSD", "isbn"=>"01-2345-6789"), 
                   array("movie"=>"batman", "date"=>"10-10-1995");

    for($x = 0; $x < count($index); $x++){
      if($index[$x]["book"] == key($assoc)){
        edit::modify(current($assoc)); //I WANT TO PASS THE REFERENCE NOT VALUE
      }                                //current(&$assoc) DOES NOT WORK 
      next($assoc);
    }
  }
}

class edit{
  public function modify(&$isbn){
    $pattern = "/[^0-9]*/";
    $isbn = preg_replace($pattern, "", $isbn);
  }
}
like image 833
Kevin Avatar asked Dec 10 '25 14:12

Kevin


1 Answers

Posting it here as reference since this was solved in the comments

doing &$assoc[key($assoc)] will solve the problem.

for($x = 0; $x < count($index); $x++){
  if($index[$x]["book"] == key($assoc)){
    edit::modify(&$assoc[key($assoc)]);
  }                                
  next($assoc);
}
like image 117
JohnP Avatar answered Dec 12 '25 03:12

JohnP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!