-1

I want do add values to array in my function to show movies:

$movies = array();

function find_movie($tag) {

    // SELECT MOVIE BY %TAG%

    $movies[] = $MOVIE;

    return '<a href="'.$MOVIE.'">WATCH MOVIE</a>';

}

Induction:

echo find_movie('cars'); // <a href="cars-movie.html">WATCH MOVIE</a>

My problem is here -> $movies array is empty... I want to have array with all movies what is showed.

How can I do that ?

coderabbit
  • 77
  • 9
  • you can do that by simply adding `global $movies` inside your function or just follow call by reference – shatheesh May 05 '14 at 17:43
  • 1
    @shatheesh: No, [don't do that](http://stackoverflow.com/a/5166527/1438393). Pass them as parameters as shown in Shankar's answer. – Amal Murali May 05 '14 at 17:47

1 Answers1

2

You need to pass the $movies array as a reference to make this work out.

Like this..

function find_movie($tag,&$movies){

and call it like..

echo find_movie('cars',$movies);

The code..

<?php

$movies = array();

function find_movie($tag,&$movies) {
    $movies[] = "<a href=$tag>WATCH MOVIE</a>";

}

find_movie('cars',$movies);
var_dump($movies);

OUTPUT:

array (size=1)
  0 => string '<a href=cars>WATCH MOVIE</a>' (length=28)
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126