Remove a letter from the alphabet with FOR

1

Hello, I need to remove a single letter from the alphabet with FOR.

I'm going through the alphabet from A to Z, but I need to take the letter Y

<?php
for($letra = ord("A"); $letra <= ord('Z'); $letra++)
{
   echo chr($letra).",";
}
?>

Expected result:

A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Z,

But until now I could not get away with getting

A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,
    
asked by anonymous 21.06.2015 / 16:33

3 answers

2

You can use a simple if for this and you can also use implode to concatenate, do this:

<?php
$todasLetras = array();

//Salvar o valor em uma variavel pode melhorar um pouco a performance
$final   = ord('Z');
for($letra = ord('A'); $letra <= $final; $letra++)
{
    $current = chr($letra);
    if ($current !== 'Y') {
        $todasLetras[] = $current;
    }
}

echo implode(',', $todasLetras);

Example online: link

    
21.06.2015 / 16:38
6

One interesting thing is that php uses the same Perl convention. for strings this means that you can increment the value a string based on the value ASCII since it is valid (65..90 A..Z, 97..122 a..z), then you can solve this problem in a different way, without using the ord () and chr () .

You can use the approach of creating an array with the letters of the alphabet with range () , then get the key that contains Y (key 24) with array_seach () just remove- unset () with either variable $item_remover or with direct index 24.

use the implode () to format the array as a string.

<?php

$alfabeto = range('A', 'Z');
$item_remover = array_search('Y', $alfabeto);
unset($alfabeto[$item_remover]);

echo implode(', ', $alfabeto);

Example - ideonline

php manual - increment operator

    
21.06.2015 / 19:18
1

In a different approach, a simplified and optimized proposal:

<?php
$remove = 'y'; 
$str = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
echo str_ireplace(array(','.$remove, $remove.','),'',$str);
?>

Okay, what's the point of modifying the original code completely?

The original code starts with redundancies:

for($letra = ord("A"); $letra <= ord('Z'); $letra++)

It will consume fewer processes if you write the entire alphabet in a string.

As the end result will be the letters of the alphabet separated by commas, with the exception of the letter to be removed, then it does not make sense to use a repeat loop to generate the string.

    
22.06.2015 / 05:28