Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
La declaración de caso de cambio de PHP da un problema en el primer ciclo

Estaba tratando de hacer algunos ejercicios en PHP para la escuela y me encontré con esto...

Mi código:

 <?php $arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ]; $item = 0; while ( $item < count($arr) ) { echo $item." - "; switch ( $item ) { case $arr[ $item ] == 5: echo $arr[ $item ]." --> This is 5<br />"; break; case $arr[ $item ] == 6: echo $arr[ $item ]." --> This is 6<br />"; break; default: echo " --> Not found<br />"; } $item++; } ?>

Este es el resultado que obtengo:

 0 - 3 --> This is 5 1 - --> Not found 2 - 5 --> This is 5 3 - 6 --> This is 6 4 - --> Not found 5 - --> Not found 6 - --> Not found 7 - --> Not found 8 - 5 --> This is 5 9 - --> Not found 10 - 6 --> This is 6 11 - --> Not found

Pero en la primera línea debería obtener:

0 - --> No encontrado

¿Por qué el interruptor no funciona correctamente?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Hiciste mal el cambio. :)

El switch ( $item ) { debe contener el ítem que está buscando.

Código fijo aquí:

 <?php $arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ]; $item = 0; while ( $item < count($arr) ) { echo $item." - "; echo $arr[$item]; switch ( $arr[ $item ] ) { case 5: echo $arr[ $item ]." --> This is 5<br />"; break; case 6: echo $arr[ $item ]." --> This is 6<br />"; break; default: echo " --> Not found<br />"; } $item++; } ?>

O esta sería otra solución (no la ideal, pero espero que esto le brinde más ejemplos :)

 <?php $arr = [ 3, 4, 5, 6, "apple", 7.2, -10, "banana", 5, 5.1, 6, "okke" ]; $item = 0; while ( $item < count($arr) ) { echo $item." - "; echo $arr[$item]; switch ( true ) { case $arr[ $item ] === 5: echo $arr[ $item ]." --> This is 5<br />"; break; case $arr[ $item ] === 6: echo $arr[ $item ]." --> This is 6<br />"; break; default: echo " --> Not found<br />"; } $item++; } ?>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!