Searching elements of a PHP array

Asked

Viewed 55 times

0

My function is this and takes a number that the user type and sees if it corresponds to a position of the matrix, if true, would display the information of the internal array, but the information is not displayed correctly:

function localizar($id){

    echo "<h2>Resultado para o id $id:</h2>";

     for($i = 0; $i < count($_SESSION['array2']); $i++){            

        if($_SESSION['array2'][$i] = $id){

            for($s = 0; $s < count($_SESSION['array1'][$i]); $s++){

                $result = $_SESSION['array1'][$id][$i];

                break;

            }


            echo $result;

        }else{                      
            echo "Não encontramos correspondências";
        }


        echo "<br>";  


    }

Matrix:

function cadastrar($nome, $raca, $cor, $tipoPelo){

    $_SESSION['array1'][] = array($nome, $raca, $cor, $tipoPelo);

    $_SESSION['array2'][] = $_SESSION['array1'];


}

How information is displayed:

Puss 1 Race 1

How they should be displayed:

Puss 1 Race 1 Colour 1 Type 1

1 answer

1

Hello,

First you will not need to loop to test if the key exists just use this function that already does this:

array_key_exists http://php.net/manual/en/function.array-key-exists.php

Knowing that the key exists just make the data go through, but I recommend you do it with foreach() and not with for(), because that way you don’t have to worry about counting the values but only going through them.

Another detail within your for() is a break; that shouldn’t be there the loop is running but is stopping because of it.

I hope I’ve helped, any doubt calls there

Browser other questions tagged

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