Jump to content

Basic array problems!


Edward

Recommended Posts

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.
Link to comment
Share on other sites

[!--quoteo(post=375080:date=May 18 2006, 11:49 PM:name=AndyB)--][div class=\'quotetop\']QUOTE(AndyB @ May 18 2006, 11:49 PM) [snapback]375080[/snapback][/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
Link to comment
Share on other sites

Those darn pesky spaces ...
You wrote:
[code]<?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;
}?>[/code]

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:
[code]<?php
if (trim($person) == 'Person1') { $number = 'Odd'; }
if (trim($person) == 'Person2') { $number = 'Even'; }
?>[/code]
for your comparison statements.

Ken
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.