Creation of Array within Function

Asked

Viewed 600 times

1

I’m trying to do an exercise where I have to create a array within a function, and the same be accessed through an external code (example: ...php? parents=uk and show United Kingdom - London).

The items of array are countries and capitals, example: Brazil - br - Brasilia, United Kingdom - uk - London, United States - us - Washington, etc.

Points of the exercise:

  • receive a country code, search it on array and write the name of the country.
  • the search has to be performed in a function.
  • the country code has to be passed the function as parameter.
  • the function has to indicate the country and the capital.

I previously did the exercise as follows (with switch), but with a array I’m not getting it, follow the code:

function paises($pais){
   switch($pais){
      case 'pt':
         $mensagem = "Portugal";       
         $mensagem2 = "Lisboa"; 
         break;

      case 'br':
         $mensagem = "Brasil";       
         $mensagem2 = "Brasilia"; 
         break;

      case 'it':
         $mensagem = "Italia";       
         $mensagem2 = "Roma"; 
         break;

      case 'uk':
         $mensagem = "Reino Unido";       
         $mensagem2 = "Londres"; 
         break;

      // ......

      default:
         echo "Nenhum país foi escolhido!";

   }         
}
  • What result do you expect to have? if possible post the code in the question instead of images!

  • Basically I am doing some exercises of php, I am learning and the exercise asks the following: https://s32.postimg.org/hg1fj72wl/exercicio.jpg I can’t post the code, because I am not at home at the moment, only at night! Thank you! @zekk

3 answers

4

One of the ways to return a array as a result of the function is:

function paises($pais){
    $resultado = [];

    switch($pais){
        case 'br':
            $resultado['pais'] = 'Brasil';
            $resultado['capital'] = 'Brasilia';
            break;

        case 'it':
            $resultado['pais'] = 'Italia';
            $resultado['capital'] = 'Roma';
            break;

        // Resto do código...   

        default:
            echo "Nenhum país foi escolhido!";
    }

    return $resultado;
}

Example of use:

$informacoes = paises('br');

if (isset($informacoes)){
    $pais = $informacoes['pais'];
    $capital =  $informacoes['capital'];

    echo $pais . "\n";
    echo $capital . "\n";
}

See demonstração

  • 1

    Thank you very much zekk, I am currently out of the house, but soon as I arrive I will try with your help and I reply here, probably that’s what I wanted!

  • but just like you did, it doesn’t access the global $_GET, does it? The exercise has to be executed in a way that puts the country code in the url

  • 1

    @Mariocaeiro I made this way only to be a functional example here. It has how to use the $_get yes.

3

Another example if you need:

  • receive a country code, search it in the array and write the country name.

    // abaixo mostra o array que o exercício pede para efetuar a pesquisa
    $paises = array(
    
       array("br", "Brasil", "Brasília"),
       array("usa", "Estados Unidos", "Washington"),
       array("tur", "Turquia", "istambul")
    
    );
    
  • the search has to be performed in a function.

  • the country code has to be passed the function as parameter.

So let’s put the array inside the function and do a search:

    function pesquisa($cod){

    // abaixo mostra o array que o exercício pede para efetuar a pesquisa
    $paises = array(

       array("br", "Brasil", "Brasília"),
       array("usa", "Estados Unidos", "Washington"),
       array("tur", "Turquia", "Istambul")

    );

    //vamos usar este array para retornar os valores
    $valores = array();

    //agora vamos varrer o array e pesquisar o código

    for($x=0; $x < count($paises); $x++){

        if($paises[$x][0] == $cod){

            $valores[0] = $paises[$x][1];
            $valores[1] = $paises[$x][2];

            break;

        } else {

            $valores[0] = false;
            $valores[1] = "Não foi possível realizar sua consulta: código incorreto ou não existe!";

        }

    }

    return $valores;

}

 print_r(pesquisa($_GET['cod']));
  • the function has to indicate the country and the capital.

When we use the url www.pesquisa.com/index.php?cod=turthe function will return:

Array ( [0] => Turkey [1] => Istanbul )

1


This is an alternative based on solution by @Andrei Coelho. I believe that more simplified.

<?php

    function pais($codigo){

        $pais = array(

        "default" => array(false, "Ocorreu um erro"),

        "pt" =>  array("Portugal", "Lisboa"),
        "br" => array("Brasil", "Brasília"),
        "it" => array("Italia", "Roma"),
        //...

        );

       return array_key_exists($codigo, $pais) ? $pais[$codigo] : $pais['default'];

    }

    // Para demonstração:
    // $_GET['pais'] = 'br';


    list($pais, $capital) = pais( $_GET['pais'] );

    // $pais será false se não houver o código!
    if($pais){


      echo $pais;
      echo '>'.$capital;

    }

?>

Your array will contain all data. The isset() will check if there is an array whose index is equal to the value of the parameter. Existing index br, in the case of this demonstration, it will return, if it will not return what is defined in default.

  • Hello Inkeliz, thanks for your help! But if I want the user to open the browser and write the address, being himself to choose a code as for example " it ", and appear parents and capital to which this code refers. for example http://localhost/test.php? parents=it (arrow_key_exist $_GET?)

  • 1

    Just change the isset to the array_key_exists. To use the $_GET['indice'] just insert into pais( $_GET['pais'] ). You can see this by working on http://sandbox.onlinephpfunctions.com/code/896c581e671207002d1f90a8940d592e8eae59eb. In this case only change the value of $_GET['pais'] to be able to visualize. I have made the necessary changes, so I believe it is the way you want it.

  • I liked your solution @Inkeliz. More simplified really.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.