Code snippet driving me mad....

HI all,
I have a small bit of PHP code that is driving me mad.

$parent_id is obtained from a value in a database.
The problem is that even when the value is 0 in the database the script doesnt seem to detect it. Ive echoed out parent_id so I know its 0. Ive tried intval($parent_id) but that doesnt seem to work.

If I put $parent_id=0; it works fine. Anyone have an idea of what Im doing wrong?

Here is the code snippet.


            if ($parent_id===0) {
                  return $title;
            } else {
                  dothis($parent_id);
            }
fox_stattonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Loganathan NatarajanLAMP DeveloperCommented:
please ensure $parent_id has value 0 or empty.. only then the condition will work properly.
0
Loganathan NatarajanLAMP DeveloperCommented:
You may use trim () or empty() function to check the value then you can use isset()
0
ienaxxxCommented:
... If I put $parent_id=0; it works fine. Anyone have an idea of what Im doing wrong?
it's cause it SETS the value to 0 while checking the ASSIGNMENT operations with "=" ends correctly.

Are you sure the $parent_id is 0 and not, for example, an array?

Try to echo $parent_id right before the check.
Try to print_r($parent_id).

What is the result?
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Chris HarteThaumaturgeCommented:
Using triple === is safe type checking. That means the value read from the database has to be an int of value zero, which is different from a char '0'.

Try it with double == and see if that works
0
Kim WalkerWeb Programmer/TechnicianCommented:
Interesting. According to PHP documentation, intval returns zero on failure. And any string beginning with a zero is treated as an octal number so I guess intval would shift to octal and return a null value for a single zero. But the documentation doesn't mention how it returns a true value of zero even if the string were "00".

Why do you need to convert it? Why not just use $parent_id === '0'?
0
Hugh McCurdyCommented:
I agree with MunterMan (before I read his post).  

Why are you using === instead of ==?  If there isn't a very good reason, please try ==.  (Even if there's a good read, try == and see if the code works and then we can discuss the reason.)
0
Ray PaseurCommented:
Please read these two pages to understand the difference between strict identicality with === and loosely typed equality with ==
http://php.net/operators.comparison
http://php.net/manual/en/types.comparisons.php

You can learn about any of your variables with this function.  It prints the type as well as the value.
http://php.net/manual/en/function.var-dump.php

All values returned from the data base are returned as strings.  They may be converted into integers or other data types, either intentionally or accidentally, by PHP type juggling.
http://php.net/manual/en/language.types.type-juggling.php

Hope that helps shed some light on it! ~Ray
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hugh McCurdyCommented:
Ray, that's a good point about the db returning strings.  Pretty concisely identifies the problem.

Hugh
0
fox_stattonAuthor Commented:
I just did the var dump and its showing int(0)

tried changing == to === but still not working.
0
fox_stattonAuthor Commented:
okl, so ive dug a little deeper and found that the match is fine.

It appears for some reason that "return $title" is not returning the variable title

So when I call the function the page using


$sys=dothis($id);
echo $sys;



it shows nothing.
0
Ray PaseurCommented:
@fox_statton: Do you know the story about the blind men and the elephant?  We are looking at fragments of information here, and "return $title" is not part of the question.  There could be any number of things wrong.  Maybe you should give us a more comprehensive overview of what you're trying to achieve.  Post the code that is failing and we might be able to tell you how to go about diagnosing and correcting the errors.  Thanks and regards, ~Ray
0
Hugh McCurdyCommented:
Is there anything in $title?

var_dump ( $title );
0
fox_stattonAuthor Commented:
yes, title is showing string(25)
0
fox_stattonAuthor Commented:
This is what my function looks like:
function find_top_parent($id) {
	$query="SELECT from database etc";

	$result=mysql_query($query);
	$num=mysql_numrows($result); 
	$i=0;

	while ($i < $num) {

		 $title=mysql_result($result,$i,"title");
		 $parent_id=intval(mysql_result($result,$i,"parent_id"));


		if ($parent_id==0) {
		echo "MATCH FOUND $title";
			return $title;
		} else {
		echo "NO MATCH FOUND";
			find_top_parent($parent_id);
		}

		++$i;
	}

}

Open in new window

0
fox_stattonAuthor Commented:
Its a recusive function that Im using to keep searching until it finds parent_id=0

then its supposed to return the title of item with parent_id=0
0
Ray PaseurCommented:
$query="SELECT from database etc";

A statement like this is virtually useless if you want help in debugging.  We really need to see accurate information.

A way to make the query and find the title and parent_id might be something like this code snippet (untested, because I do not have your data base).  I cannot see how you use the $id argument, but maybe you can provide some additional information about that.
function find_top_parent($id) 
{
    $query  = "SELECT parent_id, title FROM mytable WHERE (some clause) ORDER BY parent_id DESC";
    $result = mysql_query($query);
    if (!$result) die("$query" . mysql_error());
    while ($row = mysql_fetch_assoc($result))
    {
        if ($row["parent_id"] == 0)
        {
            return $row["title"];
        }
    }
}

Open in new window

0
Kim WalkerWeb Programmer/TechnicianCommented:
I may be stating the obvious, but why aren't you letting MySQL do the work and just select the record with parent_id 0?

SELECT * FROM table WHERE parent_id=0

Open in new window


Then you wouldn't need to find it in PHP which is a lot of unnecessary work.
0
Ray PaseurCommented:
@xmediaman: If all the SELECT queries go to the same table you may have found the magical answer!  And actually, you would only need to SELECT title from that table.

;-)

~Ray
0
fox_stattonAuthor Commented:
The reason being that each item in the database has a parent (which is another item).

For example:

id | title | parent_id
1 | Tree |0
2| | Branch | 1
3 | Twig | 2
4 | Apple | 3


When the script is called I have only information concerning one item, of example "Apple", so I want to find what the top level parent is for Apple, the item which would have a  parent_id=0

So the function is recursive and works it way through the parents of Apple, until it finds the very top one.



0
Ray PaseurCommented:
And this is in one table?  Is this by any chance a school assignment?
0
fox_stattonAuthor Commented:
Yep, its in one table. Nope not a school assigment its for a system I built a long time ago, Im sure I did something similar and it worked, but not sure why his code isnt.
0
Ray PaseurCommented:
OK, maybe we are making progress.  Can you please post the CREATE TABLE statement and tell us how many rows are in the table.   Also please tell us how many tree structures are embedded within the rows.  Thanks, ~Ray
0
fox_stattonAuthor Commented:
Hi guys,
ok managed to fix it. phew!

It was all down to the recurvie function, had to restructure it, as the variable was not being preserved. I did something similar years ago using arrays, but have obvioulsy lost some of those skillz!

Thanks for all the help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.