Access matrix within function

0

Good afternoon,

I'm setting up a naval battle and I have the following difficulty: I am not able to access a certain array created inside a function. Within the same function I call another function that accesses this array, but PHP informs that this array is not defined. Below the framework I'm doing.

//SORTEIA OS NAVIOS
	function reiniciar(){
		$navios = array();

		//ZERA A MATRIZ
		for ($l=-1; $l < 31; $l++) { 
			for ($c=-1; $c < 31 ; $c++) { 
				$navios[$l][$c] = -1;
			}	
		}

		//CHAMA AS FUNÇÕES
		sorteia(3,5,"P");//CONSTROI OS PORTA AVIÕES
    }

    function sorteia($quantidade,$n_posicoes,$embarcacao){
        if($navios[$rand_linha][$rand_coluna] == -1){
          //AQUI DIZ QUE $navios ESTA INDEFINIDO
        }
    }
    
asked by anonymous 15.06.2016 / 17:45

2 answers

0

Well, I do not know if I could explain it right by the comments so let's go.

What happens in your code is the following, are you using functions correct? So the variable you created in function reiniciar so can be used! Unless you declare it as global, then in function sorteia you get 3 variables:

 function sorteia($quantidade,$n_posicoes,$embarcacao)

You can then work with these 3 variables here because you are setting their values when calling the method:

sorteia(3,5,"P");

But% of% is the variable you use in $navios , it does not exist here because you have not passed and / or set a value for it. In case you could pass directly:

sorteia(3,5,"P", $navios);

And then get it in if :

function sorteia($quantidade,$n_posicoes,$embarcacao, $navios)

So you could work with her on function sorteia.

I hope you've been able to explain, any questions please ask

    
15.06.2016 / 18:44
0

What I'm doing:

        //CHAMA AS FUNÇÕES
		sorteia(3,5,"P",$navios);//CONSTROI OS PORTA AVIÕES
		//sorteia(5,3,"D",$navios);//CONSTROI OS DESTROIER
		//sorteia(7,2,"S",$navios);//CONSTROI OS SUBMARINOS
		//sorteia(10,1,"B",$navios);//CONSTROI OS BOTES
		
		echo "<table border='1'";
			for ($l=0; $l < 30 ; $l++) { 
				echo "<tr>";
					for ($c=0; $c < 30 ; $c++) { 
						echo "<td>";
							echo 
						echo "</td>";
					}
				echo "</tr>";
			}
		echo "</table>";
    
16.06.2016 / 01:01