f



Why strange IF...ELSE behavior

Hi all,

I'm getting a strange result with the following IF statement:

$bar = ($foo == 'last') ? true : false;

In my script $foo normaly has a integer value greater than 0, but can have
last as value. But whatever value of $foo $bar always becomes true.
When I use the regular if {....}else{....} I get the same result, always
$bar becomes true.
I've played around with a couple things, like turning the statement around
($foo != 'last') but nothing seems to give the desired result.
Can anyone tell me what I'm doing wrong or how to fix this.

Thanx,
J-P


0
6/26/2003 8:49:16 PM
comp.lang.php 32646 articles. 0 followers. Post Follow

2 Replies
1182 Views

Similar Articles

[PageSpeed] 13

J-P �crivit:

> Hi all,
> 
> I'm getting a strange result with the following IF statement:
> 
> $bar = ($foo == 'last') ? true : false;
> 
> In my script $foo normaly has a integer value greater than 0, but can
> have last as value. But whatever value of $foo $bar always becomes
> true. 

It's due to the silent type casting of php 
you should use === instead of ==


-- 
P'tit Marcel
0
6/26/2003 8:57:17 PM
>
> It's due to the silent type casting of php
> you should use === instead of ==
>

Thanx that did it, never to late to learn something.


0
6/26/2003 9:02:10 PM
Reply:

Similar Artilces:

Strange PHP behavior or not?
Why does the code below prints 'Hello' although the argument is 'abcdef'? <?php function test($argument) { if($argument == 0) { echo 'Hello'; } } test('abcdef'); ?> Thanks for your help in advance, Marcel MaMo schreef: > Why does the code below prints 'Hello' although the argument is 'abcdef'? > > <?php > > function test($argument) { > > if($argument == 0) { > echo 'Hello'; > } > > } > > test('abcdef'); > > ?> > > Thanks for your help in advance, > > Marcel > > Hi Marcel, That is because the string abcdef equals 0 if you compare like that. You can test it like this: echo (int)"abcdef"; Try it again with === instead of == to see the difference. === also does typechecking. Regards, Erwin Moller -- "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." -- C.A.R. Hoare MaMo schreef: > Why does the code below prints 'Hello' although the argument is 'abcdef'? > > <?php > > function test($argument) { > > if($argument == 0) { > echo 'Hello'; > } > > } > > test('abcdef'); > > ?> > > Thanks fo...

Strange PHP/MySQL behavior
I am working with the following script for a weblog that manipulates any combination of two variables: $postauthor and $archive. if (isset($HTTP_GET_VARS['archive'])) { $archive = $HTTP_GET_VARS['archive']; if (strlen($archive) > 15) { die("Sorry, the system cannot process your request. Please contact the webmaster."); } } elseif ((isset($HTTP_POST_VARS['archive'])) && ($HTTP_POST_VARS['archive'] != "")) { $archive = $HTTP_POST_VARS['archive']; $archive = str_replace("_", " ", $archive); } if ((isset($HTTP_POST_VARS['author'])) && ($HTTP_POST_VARS['author'] != "")) { $postauthor = $HTTP_POST_VARS['author']; } if ((isset($archive)) && (strlen($archive) == 4)) { include "./archives/$archive.php"; } else { if ((isset($archive)) && (isset($posauthor))) { $postquery = "select authors.name, posts.postid, posts.date, posts.time, posts.subject, posts.text from authors, posts where authors.authorid = posts.authorid and posts.date like '%".$archive."' and authors.name = '".$author."'"; } elseif (isset($archive)) { $postquery = "select authors.name, posts.postid, posts.date, posts.time, posts.subject, posts.text from authors, posts where authors.authorid = posts.authorid and posts.date like '%".$archive."'"; } e...

HELP: strange php behavior downloading html
This is a multi-part message in MIME format. --------------090108000902020506070203 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Please help! This MIGHT even be a bug in PHP! I'll provide version numbers and site specific information (browser, OS, and kernel versions) if others cannot reproduce this problem. I'm running into some PHP behavior that I do not understand in PHP 5.1.2. I need to parse the HTML from the following carefully constructed URI: http://crenner.smugmug.com/homepage/templatechange.mg?TemplateID=7&origin=http://crenner.smugmug.com/gallery/1960121 The problem is that when PHP downloads the HTML using file_get_contents, or any other method of opening a remote file in PHP that I have tried, it gives me the wrong page! This URI is supposed to yield the HTML from the page at http://crenner.smugmug.com/gallery/1960121 , but with the "allthumbs" version of the page, selectable from the dropdown box at the top of the page. The correct page is downloaded in IE, SeaMonkey, and in wget! But when downloading in PHP, I get the HTML from the page at http://crenner.smugmug.com/gallery/1960121 , but with the "smugmug small" version of the page, selectable from the dropdown box at the top of the page. Please note that the templatechange.mg page is merely a server-side script that takes the arguments passed to it (TemplateID and origin), and redirects the browser to the correct version of the page at &...

php bug? strange end of php file error
Why this code <?php function X() { // echo("commented ?>"); } X(); ?> give the error "Parse error: syntax error, unexpected $end" ??? ?> is into a string commented! On 07.09.2007 17:31 Fabio wrote: > Why this code > > <?php > function X() > { > // echo("commented ?>"); > } > X(); > ?> > > give the error > "Parse error: syntax error, unexpected $end" > > ??? > > ?> is into a string commented! no, it is not. There's no "strings" inside comments, comment is a stream of characters and does take ?> into account. I don't think this is a good idea either, but so is it. -- gosha bine makrell ~ http://www.tagarga.com/blok/makrell php done right ;) http://code.google.com/p/pihipi "gosha bine" <stereofrog@gmail.com> ha scritto nel messaggio news:46e17257$0$31118$6e1ede2f@read.cnntp.org... > On 07.09.2007 17:31 Fabio wrote: >> Why this code >> >> <?php >> function X() >> { >> // echo("commented ?>"); >> } >> X(); >> ?> >> >> give the error >> "Parse error: syntax error, unexpected $end" >> >> ??? >> >> ?> is into a string commented! > > no, it is not. There's no "strings" inside comments, comment is a stream > of characters and does take ?> into a...

do-while vs. if..else if...if...else..if...else if.....
Hello all, I've been working on a program, and I've come across a problem that's inherent in using if..else for program logic, and a possible solution. I don't think the solution is new, but I'd like pros, cons, and opinions from seasoned programmers. The problem: Complex if...else structures clutter up the editor, making program flow indiscernible at a glance, and can cause needless repetition. A small pseudo-code example : // a global message string // no news is *good* news... String message = ""; int Func(void *somePtr) { if (somePtr == NULL) { m...

Behaviors in Behaviors
Hi group, I'm facing this problem. I've got a behavior which makes a kind of toolbar, except the buttons on it. Within this behavior i build an element, which contains a different behavior. So far so good. everything works fine. But when i'm trying to access a method in the second behavior, i'm getting this error about an object being null. How can i access this method? i'm using this kind of construction: toolbar.close.disable(); where toolbar is the id of my first behavior, close is the id of the behavior inside the first one, and disable is a method in the second one.....

Strange, very strange
Explanation is quiet long, but finally the point is really, really strange! I'm writting some client/server application. Communication is done by simple [socket], but additionaly I use DES and bas64 from tcllib. DES is used to secure transmitted data, and base64 is to allow transmit it (data) via simple ascii-translated channel (I just need it). Now: Server-side daemon listens on some socket and when connection is estabilished it starts to sending some data (simple text) using: puts $sock [::base64::encode [::DES::des -mode encode \ -key $password $data]] Clien-side application receives it and decodes like below: set data [::DES::des -mode decode -key $password \ [::base64::decode $readData]] and finally, I get $data variable with same value as at the begining, in server-side daemon. After all of above, I do: puts "|$data| == |%|" if {$data == "%"} { puts 1 } else { puts 2 } Guess what? I see on stdout following lines: |%| == |%| 2 How about that? -- Pozdrawiam (Greetings)! Googie Dnia Sun, 17 Apr 2005 13:06:42 +0000, Googie skrobie: [...] > and finally, I get $data variable with same value as at the begining, > in server-side daemon. After all of above, I do: > puts "|$data| == |%|" > if {$data == "%"} { > puts 1 > } else { > puts 2 > } > Guess what? I see on stdout following lines: > |%| == |%| > 2 > How about that? Try to write $data to a file. Maybe it conta...

strange behavior
Hi, I ran into a strage behavior of mutt that really bugged me until I found an easy workaround. 1) type 'c' to change to a mailbox 2) type '=mailbox_X' type something 3) type tab to change to view a list of matching mailboxes 4) type 'q' - mutt returns to show 'Open mailbox: =mailbox_X' 5) type a character, e.g. 'x' - mutt deletes '=mailbox_X' and shows 'x' If you instead 5a) move the cursor 5b) type a character, e.g. 'x' - then mutt inserts 'x' into '=mailbox_X' I don't like mutt to delete...

Strange behavior
Hi all, I was still fighting for monthes with unpredicable error in my app compiled in vo27b. For example: access violation when leaving the app. This error was coming after the self:exec() of the start function (and after the queryclose of the standardshell) or HyperLabel:Axit that is not found. Today, I have imported the Manifest module. Just to try. I don't have the errors anymore... but... all my menu and look is changed... due to the windows xp style... It's a dilema: update all my menu and button.. or deal with the error ! Any suggestion ? Jean-Luc Th...

if else else
I know this idea will disturb many purists, but ..... I was wondering if there's any compelling reason not to allow a secondary-else clause in the [if] command, apart from the fact that it's generally just not done? There have been numerous cases where I've had a "if ... elseif ... elseif ... else" structure, where I've needed to do some cleanup if any of the conditions match, but not in the "else" case. A secondary else that matches if the regular one didn't (ie. if any of the regular clauses DID match) would be handy for such cleanup (or in this case, follow-up) code. It wouldn't break anything, except good style. But it would come in mighty handy... Just wondering how much of a flame I'd get for even muttering such evil thoughts... ;) Fredderic Do you mean something like this? set otherwise 0 if {$a eq "hello"} { set otherwise 1; puts Salut } elseif {$a eq "world"} { set otherwise 1; puts "tout le monde" } else { puts "autre chose" } if $otherwise { # cleanup code here ... } Fredderic wrote: > I know this idea will disturb many purists, but ..... > > I was wondering if there's any compelling reason not to allow a > secondary-else clause in the [if] command, apart from the fact that > it's generally just not done? > > There have been numerous cases where I've had a "if ... elseif ... > elseif ... else&quo...

Strange behavior
Hello I've been trying to solve the following issue on my Apache setup for a while but had no luck so far : Platform Linux RHEL 4.0 Apache 2.0.63 / PHP 5.2.5 1. wget -S http://mysite.com/index.php --22:05:35-- http://mysite.com/index.php Resolving mysite.com... xx.xx.xx.xx Connecting to mysite.com|xx.xx.xx.xx|:80... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Date: Tue, 05 Feb 2008 00:05:36 GMT Server: Apache Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, ...

about php lang
plz told me that what is the php lang., how does it works and where it used. mani <msb.jod@gmail.com> wrote: > plz told me that what is the php lang., how does it works and where it > used. There is a good explanation at http://lmgtfy.com/?q=php regards Henrik -- The address in the header is only to prevent spam. My real address is: hc3(at)poolhem.se Examples of addresses which go to spammers: root@localhost postmaster@localhost On 16 Jun 2009, mani <msb.jod@gmail.com> wrote: > plz told me that what is the php lang., how does it works and > where it used. Lulz. <http://www.google.com/> -- ~Curtis Anonymous (1984 IOCCC winner): int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\ o, world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} mani schreef: > plz told me that what is the php lang., how does it works and where it > used. http://en.wikipedia.org/wiki/Php Tip: If you want to learn something about a subject totally new to you, try wikipedia for a reasonable intro. Regards, Erwin Moller -- "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." -- C.A.R. Hoare ...

strange behavior of ??
Hi, The definition of the m?? operator says that it only matches once between calls to reset. When I ran the following program I confirmed this behavior: #!/usr/bin/perl $_ = "Bilbo Baggins"; for($i=0;$i<5;$i++) { $a = ?Bilbo?; } That is, $a was set to 1 initially and then '' on every pass through the loop afterward. However, $a does not seem to be set to 1 at all in this program: #!/usr/bin/perl $_ = "Bilbo Baggins"; for (0..4) { $a = ?Bilbo?; } Initially $a is not defined and then it stays '' on each loop pass. I am running perl v5.8...

strange behavior
I thought that output should be the same for all four lines but they differ. Am I running buggy perl? (5.8.0) use strict; use warnings; for my $i (0..3) { my $row=2; my $tmp = join ' ', map { $_ += 5*$row } 0 .. 4; print "$row - $tmp\n"; } ---------- Capture Output ---------- 2 - 10 11 12 13 14 2 - 20 21 22 23 24 2 - 30 31 32 33 34 2 - 40 41 42 43 44 -- Matija Matija Papec wrote: > I thought that output should be the same for all four lines but they differ. > Am I running buggy perl? (5.8.0) > > > use strict; > use warnin...

Strange behavior
Why if, f.e., if I write in the page: var r = (document.referrer).toLowerCase(); var p = r.split("middle")[1]; document.write("-->"+p); it works but if I put this script in an external script and insert into multiple pages with <script src="my.js"></script> it doesn't? Help appreciated. Regards. -- Fabri ("Sono pi� di 30 punti...ma � come se fossere 8 o 9....") The code is fine, so long there's a document.referrer you can grab off the window.history stack, document.referrer returns the previous url in the history o...

Strange, strange...
Hi All, I posted this already today and I am really getting bananas with this issue: Using Visual Basic 6.0, I am sending SMS. These SMS can be added to an Access 2000 table by users on the network. Everything works well when executing the code step by step (F8). I can trace this in the Access table, that reacts exactly according to what I was expecting. But, but.... When running the code, it looks like the records in Access are not updated quickly enough and, therefore, the SMS are sent more than once (up to 10 times for some). Here is how I open the table in the Access MDB: Dim Db2 As Dat...

Strange behavior...
Hello, I have a report which is based on a query...in the query there are the following fields: 'StartDate', 'EndDate', 'CurrencyPeriod', ... in the report I have a header (dateHeader) which contains 3 textboxes: the first two are bound to 'StartDate' / 'EndDate' but the third textbox is unbound. The problem is now that I have absolutely no access to the field Me![CurrencyPeriod] in the dateHeader_Format-Event, I always get "Microsoft Access can't find the field 'CurrencyPeriod' referred to in your expression" (Runtime-Error 2465)....

Strange behavior
I have one 2k access db with one table in it. Pc is w2k pro. When I try to update a field (whichever) through Access via Data-view (not SQL view) Access itself converts values from 'UD' to 'DU'. This happens ONLY on this client and ONLY for this type of value (UD) What is it? Any help much appreciated. Regards. -- Fabri (Incredibile come si tenda a credere di piu` a Rossi. (cit.)) "Fabri" <no@sp.am> wrote in message news:310sdrF34j744U1@uni-berlin.de... > I have one 2k access db with one table in it. > > Pc is w2k pro. > > > When I try to update a field (whichever) through Access via Data-view > (not SQL view) Access itself converts values from 'UD' to 'DU'. > > This happens ONLY on this client and ONLY for this type of value (UD) > > What is it? Office Auto-Correct settings I would guess. -- I don't check the Email account attached to this message. Send instead to... RBrandt at Hunter dot com ...

Strange behavior in run-time vs. dbx behavior when using shmget
Hi, I have a very strange problem, and i don't know what is the reason for it. I'm using an AIX 5.1 over power_604. In my hi-level program (written in c), I'm writing some machine commands to 0x60000000 segment using shmget and shmat, and after it, in the assembly code, I'm adding only 2 commands which are; mtlr xxx //where xxx holds 0x60000000 brl The purpose of this code is to branch to segment 0x60000000, executing some machine commands, and from there returning to the branching procedure. If i run this application using dbx, it works fine. I run time, however, after execu...

very strange ksh behavior
This is a very strange problem. $ while read line > do > rc=$(echo $line | awk '{ print $4 }') > echo BEFORE rc is $rc > if [ "$rc" -ne 0 ]; then echo " ERROR rc nonzero rc is $rc"; fi > echo AFTER rc is $rc > done extract4 status: file=file1.txt rc=0 realcount=488 BEFORE rc is rc=0 AFTER rc is 0 extract4 status: file=file2.txt rc=2 realcount=223 BEFORE rc is rc=2 ERROR rc nonzero rc is 2 AFTER rc is 2 extract4 status: file=file3.txt rc=0 realcount=992 BEFORE rc is rc=0 AFTER rc is 0 $ uname -a AIX dscnd002 3 ...

Strange AirPort behavior
All of a sudden the Airport stuff I have set up at home is going a little nuts. On both laptopsthat we use at home (one has an old Airport card, the other has the newer Airport Extreme) the Airport icon is starting to flash on and off, going from 5 bars to 0 bars in rapid succession. Setting "Use Interference Robustness" on my machine helps sometimes, but my wife's machine (the older one, still running Panther) doesn't even seem to have that option. Can someone suggest what might be going on and offer a possible solution? Thanks!! Lot-o-fun <lotofun61@yahoo.com> wr...

Strange IE behavior
I've already resolved this for my part, but I think others may need to know about it, in case something similar happens to them. As part of a website development, I wrote a PHP file which worked just fine under Firefox and Opera, but dropped the session under IE. It took me ages to track this down. Here's what happened. The URL for the main page was set up so that if it was called without GET parameters, it would start a new session. In the normal course of operation, the main page gets called back with a GET parameter of the form '? mode=something', which was used by the PHP code to determine the context in which the page should be run. This worked fine under Firefox etc., but failed miserably and frustratingly under IE. After months of effort, I discovered the explanation. IE was requesting the page twice for each call, once with the GET parameter in the URL, and the second time without any GET parameters. The server handled each of these requests as you might expect -- it executed the PHP code twice, the second time without the GET parameters, which caused it to terminate the current session. There was no evidence of the second call anywhere on the screen -- it's entirely unclear to me what purpose the second request might have served. Once I figured this out, I worked around it. So be warned. Under at least some circumstances, whenever you (or one of your users) requests a PHP page, IE will request it twice, which at the very least will cause a perfo...

Strange behavior with screens
I'm creating an application with forms using panel controls, when I compile the application and run it.. it shows the forms with different sizes and the control panels moved and also different size. When I go back the design it shows the form as it should be... Try many times erasing and creating again but it gives the same problem... I'm using Windows XP Pro and CEE 6.1. Can somebody please help me? Hi Enrique, My best guess is that you need to delete the .ini file that sets the screen postion of the window screen controls. The .ini file name is probably <appname>.ini and it is located either in the development directory along with the .app file or in the C:\Windows directory. There is a free template in the BoTpl template set at http://www.comsoft7.com/Prices.htm you can use to "reset" this ini file from within your .app file with a "special version" number for the template. Be sure to look over all the rest of the free templates in BoTpl too. HTH -- Best Regards, Earl R Coker ksasales AT machlink DOT com kwiksys AT kwiksystems DOT net www.kwiksystems.net www.kwiksystems.com www.kwiksystems.net/appshell/index.htm www.kwiksystems.com/clarion.htm (BigTamer(tm) Templates) "eguevara" <enrique.guevara@megared.net.mx> wrote in message news:1120846120.793738.28900@o13g2000cwo.googlegroups.com... : I'm creating an application with forms using panel controls, when I : compile the application and run it.. it shows the for...

strange performance behavior
Hi, on my Debian machine (2 CPUs, SMP kernel running) I observe a strange system behavior (top output): top - 10:08:18 up 3 days, 15:59, 5 users, load average: 2.87, 2.89, 2.35 Tasks: 107 total, 1 running, 106 sleeping, 0 stopped, 0 zombie Cpu0 : 11.3%us, 0.8%sy, 0.0%ni, 87.7%id, 0.1%wa, 0.0%hi, 0.1%si, 0.0%st Cpu1 : 16.9%us, 1.1%sy, 0.0%ni, 81.6%id, 0.3%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 8253752k total, 5390448k used, 2863304k free, 282268k buffers Swap: 7815612k total, 0k used, 7815612k free, 4873248k cached As you can see the load values are relatively...

Web resources about - Why strange IF...ELSE behavior - comp.lang.php

Behavior - Wikipedia, the free encyclopedia
Behavior or behaviour (see spelling differences ) is the range of actions and mannerisms made by individuals, organisms , systems , or artificial ...

Behavior Design - behaviordesign.com
Behavior designs interactive systems.

Behavior Gap - Exploring the relationship between people and their money. Behavior Gap
Watch it now. Watch the latest videos by Carl Richards on money, emotion, and meaningful conversations.

Dog Behavior Tips -Dog Owners One Stop Shop and Tips
Come and get some free dog behavior tips. Training your new or older dog can sometimes be somewhat of a task if you are new to doing it. Let ...

Modeled Behavior
It is, more or less, the country’s primary check for determining how well the government is doing — and in fact what the government will be doing. ...

Online Behavior - Marketing Measurement & Optimization
This website is a source of knowledge for website owners and analysts looking to understand how their online customers behave . But that's not ...

BJ Fogg's Behavior Model
... In addition, he devotes at least half his time to industry projects and innovations, all of which focus on using technology to change behaviors ...

Plant Behavior
The Society of Plant Signaling and Behavior serves the community of scientists interested in sensory plant biology, signaling, information processing ...

Lawyers Say They Have Emails Showing JWT Was Told About Exec's Behavior
Lawyers for JWT Chief Communications Officer Erin Johnson say they have an email exchange documenting their client's attempts to alert the agency ...

Facebook’s ad platform now guesses at your race based on your behavior
N.W.A. in the late 1980s. Three different versions of the marketing campaign for the band's biopic Straight Outta Compton appeared on Facebook: ...

Resources last updated: 3/24/2016 7:13:04 AM