James
James

Reputation: 43657

Search for specific symbol inside array

$array = array('a', 'b', 'c', 'd', /*... letters from 3 alphabets*/);

$letter = 'some symbol, posted by user'; // real length = 1

How to get know, is $letter one of the symbols, listed in $array?

Like, if $letter = 'G' and there is no G in $array, well then return false.


Yep, I tried in_array(), but there are too many symbols, is there any other (shorter) solution?

Upvotes: 3

Views: 214

Answers (4)

Angelo R.
Angelo R.

Reputation: 2341

in_array() http://ca.php.net/in_array

if(in_array($letter,$array)) {
  // your code
}

Another method would be to do this

// THIS WAY
$array = array('a','b','c'); // and continue this way. 
$array = array_flip($array);

// OR THIS
$array = array('a'=>0,'b'=>0,'c'=>0);

// This will stay the same
if($array[$letter] != null) {
  // your code
}

Upvotes: 4

NikiC
NikiC

Reputation: 101936

You could use a string instead of an array:

$letters = 'abcdefghi...';
$letter = 'a';

if (false !== strpos($letters, $letter)) {
    // valid letter
}

Upvotes: 0

Coach John
Coach John

Reputation: 327

Check the in_array() function ... lets you find a needle (single letter) in a haystack (an array)

Upvotes: 0

d2burke
d2burke

Reputation: 4111

$IsInArray = in_array($letter, $array); //RETURNS TRUE OR FALSE

Upvotes: 0

Related Questions