Remove a letter from the alphabet with FOR

Asked

Viewed 1,202 times

1

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

I’m going through the alphabet from A to Z, but I need to get 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 so far I couldn’t get it out by staying

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,

3 answers

7

An interesting thing is that php uses the same convention of Perl for strings this means that you can increment the value of a string based on the value ASCII as long as it is valid(65.90 A..Z, 97..122 a..z), it is soon possible to solve this problem in another way, without the use of functions Ord() and Chr().

You can use the approach of creating an array of alphabet letters with crease(), then get the key containing the Y (key 24) with array_seach() just remove it with unset() either with 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

2


You can use a if simple for this and can also use the 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);

Online example: https://ideone.com/nCVno7

1

In a different approach, a simplified and optimised 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, why modify 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 whole alphabet in a string.

As the end result will be comma-separated alphabet letters, with the exception of the letter to be removed, so it makes no sense to use a repetition loop to generate the string.

Browser other questions tagged

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