I'm very new to PHP
and I found a problem which I can't find much information, something that I really understand or that helps me for my level; I have two FOREACH (Which I have never used in another language), these print a table in HTML
and I need to completely ignore the last field (I WANT ALL THE DATA TO BE DISPLAYED EXCEPT THE LAST OF EACH CYCLE ["G.Img"] ) ; I have tried the CONTINUE; but really the problem is the If , it doesn't work for me with anything; I have tried too many ways.
HERE I LEAVE MY LITTLE CODE WITHOUT WORKING:
<?php
foreach($paises As $x){
//DEBERÍA IGNORAR EL ÚLTIMO DATO Y SEGUIR EL CICLO
//INTENTO FALLIDO:
if(array_keys($x) == 6){
echo "Entró";
continue;
}
foreach($x As $x1){
//CÓDIGO PARA IMPRIMIR LOS DATOS INTERNOS DE LOS PAÍSES.
//-------------
//-------------
}
}?>
I also attach the shape of my associative arrays:
$paises = array(
"Chile" => array(
"Bandera" => "<img src='../SOURCES/cl.png'>",
"Nombre" => "República de Chile",
"Moneda" => "CLP",
"Comida" => "Ajiaco","Chorillana","Sopaipillas",
"G. Img" => "<img src='1.png'>", "<img src='1.png'>", "<img src='1.png'>"
),
"Japón" => array(
"Bandera" => "<img src='../SOURCES/jp.png'>",
"Nombre" => "Estado del Japón",
"Moneda" => "YEN",
"Comida" => "Ramen","Onigiri","Yakitori",
"G. Img" => "<img src='1.png'>", "<img src='1.png'>", "<img src='1.png'>"
);
Thanks in advance :( !
First, the condition for the output should be in the second
foreach
, not the first, since it is in the second that you loop through the country data.Second, in this case you want to avoid a particular element, which happens to be the last one in the array. It will be easier for you to avoid that element by its key, since you know what it is
G. Img
.For that you can use to include
$key
in theforeach
:However, I also show you how to do it excluding the last element, for that you need a counter:
You could also use a normal loop
for
, where you would already declare the counter, but hey, no more messing around. The first example is the best solution.Another thing, surely you want to paint the name of each country, for that you can
$key
also use in the first loop. But$key
we are going to call$pais
that one, so it is clearer and also it does not collide with the variable name of$key
the second loop. With what you would have left like this:Note : I have put very simple echoes as an example.
Good day,
Another option instead of using a counter is to use the function
end
that checks if an element is at the end of an array:This prints the keys of all but the last element.
Note: no formatting or anything, it was just a simple example.
Additional note: If you control the information and order of the array, you could use some method to discard the last element of the array, but if they are likely to have a different order then I think the best option would be to search for the key as @JoseCarlosPHP mentions in his first example.