473,581 Members | 2,785 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 9595
pe**********@ya hoo.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 PrintArrayEleme nt()
{
//$this->mArray['foo']=3;
echo $this->mArray['bar'];
}
}

$my_class = new MyClass;
$my_class->PrintArrayElem ent();

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:
@$strUrlParamet er=$_GET['Command'];
if(is_null($str UrlParameter))
...

Best regards

pe**********@ya hoo.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 PrintArrayEleme nt()
{
//$this->mArray['foo']=3;
echo $this->mArray['bar'];
}
}

$my_class = new MyClass;
$my_class->PrintArrayElem ent();

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


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:
@$strUrlParamet er=$_GET['Command'];
if(is_null($str UrlParameter))
...

[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_handl er("my_error_ha ndler", E_ALL);

function my_error_handle r($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
108830
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 work fine, but with error reporting at all they are marked as errors. Why? What am I doing wrong? www.monkeyclaus.org
9
1861
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 behavior but would like another set of eyes to check. #include <math.h> #include <stdlib.h> extern float window;
45
4813
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 "new Array() vs " question or to the array performance, I dared to move it to a new thread. Gecko takes undefined value strictly as per Book 4,...
7
2200
by: deepak | last post by:
Using 'char' as an array index is an undefined behavior?
15
4458
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 enased whitespace (to my best memory) AT other times I get an undefined index notice as below: Notice: Undefined index: last_reminder_id in...
5
7352
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 : $http_ref= $HTTP_REFERER; $prog = $_COOKIE;
5
1990
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 is conditional to my results I do not know in advance how many loops I need. The matrices are Nx * Ny* Nz*6. In C I put my matrices into 1D...
4
6293
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 Notice: Undefined index: args in /home/mattehz/public_html/acssr/trunk/inc_error.php on line 92 Warning: Invalid argument supplied for...
1
6457
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 = $parent->childNodes; need help. my site worked fine on my localhost but when i uploaded it to my live server i keep getting this error need help to recode line...
0
7804
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7910
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8180
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5681
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3832
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1409
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.