473,320 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

undefined array index question

Hi,

I am curious about how php deals with the following situation where I
use an undefined index into an array. PHP seems to be behaving exactly
how I want it to but I want to make sure that it is not a fluke. It
seems like most programming languages would crash if you used an
undefined index. Why does PHP work the way it does?

My example is below

Thanks,
Peter

<?php

$array['foo']=3;
echo 'M'.$array['foo'].'M';
//How can I index into the array to an index that doesn't exist?
echo 'M'.$array['bar'].'M';

//output
//M3MMM
//note there is no space between the last two M's
//this is exactly the result I want but why does it work?
?>

Sep 17 '05 #1
9 9584
pe**********@yahoo.com said the following on 17/09/2005 17:47:
Hi,

I am curious about how php deals with the following situation where I
use an undefined index into an array. PHP seems to be behaving exactly
how I want it to but I want to make sure that it is not a fluke. It
seems like most programming languages would crash if you used an
undefined index. Why does PHP work the way it does?

My example is below

Thanks,
Peter

<?php

$array['foo']=3;
echo 'M'.$array['foo'].'M';
//How can I index into the array to an index that doesn't exist?
echo 'M'.$array['bar'].'M';

//output
//M3MMM
//note there is no space between the last two M's
//this is exactly the result I want but why does it work?
?>


The only reason nothing breaks is because you must have PHP
error-reporing disabled.

If you had error-reporting enabled, you'd see a message like:

Notice: Undefined index: bar in D:\htdocs\Test\08.php on line 5

--
Oli
Sep 17 '05 #2
How do I enable error reporting?

Thank,
Peter

Sep 17 '05 #3
Oops. I have figured out how to test this problem with error-reporting
enabled.

However it looks like I over simplified my problem and my question
still remains. Here is an improved version of my question. In the
following code there are no errors reported. However, if I uncomment
the one comment then I will get an error "Undefined index: bar ".

Any ideas why I can use the undefined index 'bar' in $this->mArray as
long as $this->mArray has never been initiated/used?

Thanks again,
Peter

class MyClass
{
private $mArray;

public function PrintArrayElement()
{
//$this->mArray['foo']=3;
echo $this->mArray['bar'];
}
}

$my_class = new MyClass;
$my_class->PrintArrayElement();

Sep 17 '05 #4
That is because PHP casts variables as needed. Lots of other programming
languages do this also. This means that you can compute 2 + '3' and get
5, because the string is converted to an integer. I personally hate
this, because computing '3' + 2 gets '32'. Which can be converted in a
later expression to 32!
The non-existing variable is evaluated as NULL with a warning, not a
fatal error. NULL gets cast to an empty string, which is "glued" between
the 'M' strings. If you don't want the warning, you can temporarily
switch it off by putting a '@' character in front of the expression or
the command, like
@$result=mArray['NonExistingKey'];
echo 'M' . $result . 'M';

You can use this feature to check if variables exists in a quick-and
dirty way:
@$strUrlParameter=$_GET['Command'];
if(is_null($strUrlParameter))
...

Best regards

pe**********@yahoo.com wrote:
Oops. I have figured out how to test this problem with error-reporting
enabled.

However it looks like I over simplified my problem and my question
still remains. Here is an improved version of my question. In the
following code there are no errors reported. However, if I uncomment
the one comment then I will get an error "Undefined index: bar ".

Any ideas why I can use the undefined index 'bar' in $this->mArray as
long as $this->mArray has never been initiated/used?

Thanks again,
Peter

class MyClass
{
private $mArray;

public function PrintArrayElement()
{
//$this->mArray['foo']=3;
echo $this->mArray['bar'];
}
}

$my_class = new MyClass;
$my_class->PrintArrayElement();

Sep 17 '05 #5
>You can use this feature to check if variables exists in a quick-and
dirty way:
@$strUrlParameter=$_GET['Command'];
if(is_null($strUrlParameter))


That is dirty :) Probably a little better like this:

if(isset($_GET['Command')) {
//do something
}

Sep 17 '05 #6
Dikkie Dik wrote:
[snip]
The non-existing variable is evaluated as NULL with a warning, not a
fatal error. NULL gets cast to an empty string, which is "glued" between
the 'M' strings. If you don't want the warning, you can temporarily
switch it off by putting a '@' character in front of the expression or
the command, like
@$result=mArray['NonExistingKey'];
echo 'M' . $result . 'M';

You can use this feature to check if variables exists in a quick-and
dirty way:
@$strUrlParameter=$_GET['Command'];
if(is_null($strUrlParameter))
...

[snip]

"isset" can also be used for this, which will suppress warning for
non-existent index. However "isset", or the code ove, will not tell
the difference between, an existing index assigned a NULL-value, and a
non-existing index.
That is probably also the point with accepting a non-existing index as
non-fatal. That is, why enforce a verification of an index, when
validation of its value is just as important. But as it just might be
a mistake, a warning is in order.

/Bent
Sep 17 '05 #7
Dikkie Dik wrote:
... Lots of other programming
languages do this also. This means that you can compute 2 + '3' and get
5, because the string is converted to an integer. I personally hate
this, because computing '3' + 2 gets '32'. Which can be converted in a
later expression to 32!


I was thinking too much about java and Visual Basic. PHP doesn't want to
"add" strings at all, so '3' + 2 gets 5.
Sep 17 '05 #8
On Sat, 17 Sep 2005 23:02:20 +0200, Dikkie Dik wrote:
I was thinking too much about java and Visual Basic. PHP doesn't want to
"add" strings at all, so '3' + 2 gets 5.


try with this:

<?php
$a=3 . 2;
print "$a\n";
?>
--
http://www.mgogala.com

Sep 17 '05 #9
I am trying to get a message something like your Notice message. What
do I need to change about my error handler? I thought my error handler
would catch Errors, Warnings, User Notices and Notices.

Thanks,
Peter

<?php

set_error_handler("my_error_handler", E_ALL);

function my_error_handler($errNo, $errStr, $errFile, $errLine)
{
$error_message = "\nERRNO: ". $errNo ."\nTEXT: " . $errStr . " \n" .
"LOCATION: " . $errFile . ", line " . $errLine . ", at "
..
date("F j, Y, g:i a") . "\n\n";
echo "<pre>" . $error_message . "</pre>";
exit;
}

$array['foo']=3;
echo 'M'.$array['foo'].'M';
//How can I index into the array to an index that doesn't exist?
echo 'M'.$array['bar'].'M';
?>

Sep 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: lawrence | last post by:
I just switched error_reporting to ALL so I could debug my site. I got a huge page full of errors. One of the most common was that in my arrays I'm using undefined offsets and indexes. These still...
9
by: Alan Schroeder | last post by:
The following code produces the expected results on a PC using gcc, but I need to port it (or least something similar) to a different platform/compiler. I don't think I've introduced any undefined...
45
by: VK | last post by:
(see the post by ASM in the original thread; can be seen at <http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/3716384d8bfa1b0b> as an option) As that is not in relevance to...
7
by: deepak | last post by:
Using 'char' as an array index is an undefined behavior?
15
by: bill | last post by:
I am trying to write clean code but keep having trouble deciding when to quote an array index and when not to. sometimes when I quote an array index inside of double quotes I get an error about...
5
by: Pseudonyme | last post by:
Dear All : Ever had an httpd error_log bigger than the httpd access log ? We are using Linux-Apache-Fedora-Httpd 2006 configuration. The PHP lines code that lead too tons of errors are : ...
5
by: adinda | last post by:
So what i need is this; (I'm very new at this,, programming in C I mean...) In matlab I had a while loop, and after each loop was done I added my resulting matrix to an object. Seeing the loop...
4
by: mattehz | last post by:
Hey there, I am trying to upload old source files and came across these errors: Warning: Invalid argument supplied for foreach() in /home/mattehz/public_html/acssr/trunk/inc_html.php on line 59...
1
by: Beamor | last post by:
function art_menu_xml_parcer($content, $showSubMenus) { $doc = new DOMDocument(); $doc->loadXML($content);//this is the line in question $parent = $doc->documentElement; $elements =...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.