Jump to content


Photo

Basic array problems!


  • Please log in to reply
3 replies to this topic

#1 Edward

Edward
  • Members
  • PipPipPip
  • Advanced Member
  • 119 posts
  • LocationSouthampton

Posted 18 May 2006 - 10:33 PM

Here is the code I am using:

$members = 'Person1, Person2';
$array = explode(',',$members); //this creates an array by exploding your addresses at the character ','
foreach ($array AS $person) {
if ($person == 'Person1') { $number = 'Odd'; }
if ($person == 'Person2') { $number = 'Even'; }
$body = 'Hi there ' . $person . ', you are ' . $number;
echo $body;
}

Here is the desired outcome:
Hi there Person1, you are Odd
Hi there Person2, you are Even

Here is the ACTUAL outcome:
Hi there Person1, you are Odd
Hi there Person2, you are Odd

Can anyone see what I'm doing wrong? I'm trying to create a basic code I can use to specify one variable depending on what aother is, inside a loop.

#2 AndyB

AndyB
  • Staff Alumni
  • Advanced Member
  • 5,465 posts
  • LocationToronto

Posted 18 May 2006 - 10:49 PM

I can't see the difference between the actual outcome and the desired outcome Maybe we need a different example??
Legend has it that reading the manual never killed anyone.
My site

#3 Edward

Edward
  • Members
  • PipPipPip
  • Advanced Member
  • 119 posts
  • LocationSouthampton

Posted 18 May 2006 - 11:00 PM

[!--quoteo(post=375080:date=May 18 2006, 11:49 PM:name=AndyB)--][div class=\'quotetop\']QUOTE(AndyB @ May 18 2006, 11:49 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
I can't see the difference between the actual outcome and the desired outcome Maybe we need a different example??
[/quote]

Sorry, I'm tired, I've amended it now.

Here is the ACTUAL outcome:
Hi there Person1, you are Odd
Hi there Person2, you are Odd

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 19 May 2006 - 12:35 AM

Those darn pesky spaces ...
You wrote:
<?php
$members = 'Person1, Person2';
$array = explode(',',$members); //this creates an array by exploding your addresses at the character ','
foreach ($array AS $person) {
if ($person == 'Person1') { $number = 'Odd'; }
if ($person == 'Person2') { $number = 'Even'; }
$body = 'Hi there ' . $person . ', you are ' . $number;
echo $body;
}?>

Notice you have a space after the comma, so the second member of the array is really ' Person2'. That's why the "if" fails. Remove the space or use:
<?php
if (trim($person) == 'Person1') { $number = 'Odd'; }
if (trim($person) == 'Person2') { $number = 'Even'; }
?>
for your comparison statements.

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users