Difficulty choosing the correct Strings function

Asked

Viewed 44 times

0

I have an exercise to solve and I’m having some difficulty.

That is the statement of the problem:

Print the students' names again in order of enrollment, but only those whose initial letter is different from "T".

This is my code.

$nomes = array('andre' => 1 , 'paulo' =>5, 'fabio' => 2,'tiago' => 4);
asort($nomes);
foreach ($nomes as $key => $value) {
  echo 

I read the PHP manual and checked the various functions for string. I even tried some of them like count_chars(), str_word_count, without success. Can someone help me and explain if possible where I am making the mistake and what would be the right function.

1 answer

2


Every interaction of your loop foreach the variable $key will receive the index value of your array and the variable $value shall receive the amount contained. Then you need to check the first letter of each word provided as index of your array, for this we use the variable $key and the function strcasecmp php native, which compares strings without differentiating between uppercase or minuscule letters.

<?php
      $ord_nomes = array();
      $nomes     = array('andre' => 1 , 'paulo' =>5, 'fabio' => 2,'tiago' => 
      asort($nomes);
      foreach ($nomes as $key => $value){  
        if(strcasecmp($key[0],"t") != 0){
           echo  "O valor é: ".$value." e o índice é ".$key."<br/>";
        }
      }
?>

If $key receives the value of the initial that is the name, so $key[0] contains the first letter of the word. Aware of this, we assign the second parameter of the function to the letter T and make the comparison. If $key[0] is different from the letter T we print the student’s name, otherwise we ignore the print.

Em funcionamento

  • Rafael his explanation was TOP!!!. I was just wanting to understand with making such a comparison. It helped a lot in my studies. Big hug

Browser other questions tagged

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