/    Sign up×
Community /Pin to ProfileBookmark

Array problem – no. 2

What am I doing wrong here ?

[code=php]
$operator = “randomtxt”;
$i = 1;

foreach ($_GET as $key => $value) {
if (stristr($key,’phone’) && (strlen($value) > 0)) {
echo $i;
if ($i == 1) {
$operator=””;
}
$what .= ” “.$operator.” `handsets` LIKE ‘%”.$value.”%’ “;
echo $operator;
$i++;
}
[/code]

the echo from $i outputs “1234” so it goes up each time, however it sets $operator = “” in each loop, so operator is always empty, even though it’s if $i == 1 and $i is sometimes equal to 2 or 3!!

Wel confused, can’t think what i’ve missed now!

Thank you ?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@andre4s_yJul 09.2008 — When you run your code for the first time, it will set :
<i>
</i>$operator = "randomtxt";

After that, it will loop via foreach.

When it first loop, and when $i==1, in will redefine $operator
<i>
</i>$operator = "";

So the rest of foreach, $operator will empty...

No wonder about that...

The answer is : do not redefine $operator, but modify $what.

Hope this help you.

Note : [OOT]

Your mirror avatar is not correct.... It is still mirroring registered user that you have already changed it. ?
Copy linkTweet thisAlerts:
@Phill_PaffordJul 09.2008 — Looks like you don't set operator again after it's equal to ""

Your code
[code=php]
// You set $operator here
$operator = "randomtxt";

// Counter is set
$i = 1;

// Loop through array

foreach ($_GET as $key => $value)
{
// Some soft of check/validation
if (stristr($key,'phone') && (strlen($value) > 0))
{
// Print $i to the screen, this is set to 1 on the first loop
echo $i;

// so the condition is met on the first loop
if ($i == 1)
{
// Reset $operator to ""
$operator="";

// Looks like you need an else condition to
// reset the $operator to something
}

// $operator will be "" unless reset to another value
// regardless of the value of $i
$what .= " ".$operator." handsets LIKE '%".$value."%' ";

// Should print ""
// Never gets reset
echo $operator;

// Increment
$i++;
}
[/code]


Hope this helps
Copy linkTweet thisAlerts:
@GavinPearceauthorJul 09.2008 — *slaps himself* :o

thanks very much guys ?
×

Success!

Help @GavinPearce spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...