简体   繁体   中英

How to show single result on foreach loop php

I have data like this:

echo var_dump($rank);

int(13) int(3) int(5) int(1) int(2) int(7) int(8) int(4) int(10) int(14) int(12) int(9) int(6) int(11)

=======================================================================================================
echo var_dump($id_student);

string(2) "18" string(2) "19" string(2) "20" string(2) "21" string(2) "22" string(2) "23" string(2) "24" string(2) "25" string(2) "26" string(2) "27" string(2) "28" string(2) "29" string(2) "30" string(2) "31"

=======================================================================================================
echo var_dump($student_name)

string(22) "ALIFIO RULISTIAN PUTRA" string(26) "ALVIAN CHARIS JANUAR MUKTI" string(17) "AMINATUL LISTYANI" string(26) "CANTIKA RAHMAWATI SULISTIO" string(16) "CITRA WULAN ASIH" string(18) "HANIFAH ANINDITIYA" string(16) "INTAN FITRI AINI" string(17) "JULIA AYU YOLANDA" string(22) "LINTANG CAHYA WARDADNI" string(21) "LULUK ILHAMNUN AZIZAH" string(19) "MUHAMMAD FEBRIYANTO" string(21) "NAUVAL BAYU PAMUNGKAS" string(22) "SECHAR NURUL DAMAYANTI" string(22) "SEKAR ADINDA PRAMUDITA"

I use Foreach to get the same index from $ rank and $ id_student :

foreach($id_student as $index => $student){
    echo var_dump($student.' rank is '. $rank[$index]);
}

Then how do I if I only want to display single result not loop result, for example to display the ranking of $ student_name:

ex = ALIFIO RULISTIAN PUTRA Rangking Is 13

There are 2 main approaches to this, first for a one off use is to use array_search() to find the element and echo out the corresponding rank...

$find_name = "ALIFIO RULISTIAN PUTRA";

$element = array_search($find_name, $student_name);
// Check found
if ( $element !== false )   {
    echo "{$find_name} ranking is {$rank[$element]}".PHP_EOL;
}

Next creates a combined array, better if repeated searches are used, using array_combine() to create an array of ranks indexed by the names...

$stundent_rank = array_combine($student_name, $rank);
echo "{$find_name} ranking is {$stundent_rank[$find_name]}";
$index = n; // specific index
echo $student_name[$index] Rangking Is $rank[$index]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM