Web Hosting Talk







View Full Version : Php Question Re: If & Else


Rob83
04-03-2005, 11:02 AM
Hey Guys,

Was wondering if someone can help me. I'm not *that good* in Php, but I can some basic stuff and I'm pretty sure I know the answer, but maybe I'm doing something wrong. Ironically, I'm taking a C++ course at the moment and it C++ is so similiar to php (or vise versa), so I may be getting confused on my commands.

Let's assign variables:

Let's say:

I have an array ("A", "B", "C", "D")

The array is assigned to $letter. And my script will do some work and assign $letter to one of the arrays (either A, B, C, D). Now $letter can BE all of them. It can be A & B, or A &C or A &D or A,B,C,D.

I have php script that has (not completely written on in php)

if $letter == "A"
echo "letter A!";

else if $letter == "B"
echo "letter B!";

and so on!

Now.. here is my question.

Is there a way that if $Letter equals more than 2, that I can have it's own if?

Like:

if $letter == "A" | $letter == "B";
echo "Letter A and B!"

But I have so many arrays, that I can't sit there and define both "A" and "B". So I would like to be something like this:

So would I use if $letter > 2
echo "$letter"

if $letter > 3
echo "$letter"

Is that right??

Dan L
04-03-2005, 11:18 AM
<?php
$letter = array(values);
if(count($letter) == 1)
{
echo $letter[0];
}
elseif(count($letter) == 2)
{
echo $letter[0].' '.$letter[1];
}
?>It would be something like that. If this is what you're trying to achieve, you can PM me with specific problems.

N9ne
04-03-2005, 11:36 AM
Is $letter ALWAYS an array? If so, you can just do this:


<?php
$letter = array('A', 'B', 'C', 'D');

if (is_array($letter) and count($letter) > 0)
{
foreach ($letter as $l)
{
echo $l . '<br />';
}
}
else
{
echo 'Error: $letter is not an array, or is empty.';
}
?>

CSD_Hosting
04-03-2005, 03:00 PM
if $letter == "A" | $letter == "B"
echo "Letter A and B!"

should be

if( $letter == "A" || $letter == "B")
{
echo "Letter A and B!";
}


you need two pipes ( | ) and you cant end the IF with a semicolon. A semicolon is a command, so you will never reach your echo statement

mfonda
04-03-2005, 08:22 PM
the in_array() function could be useful here as well.

Burhan
04-05-2005, 03:55 AM
Perhaps the most simple way to do this is :


<?php

$letters = range('A','Z');
$search_for = "Q";
echo implode(" ",array_slice($letters,0,array_search($search_for,$letters)+1));

?>


If you want the result to NOT include the key, remove the +1