Created
March 29, 2011 11:55
-
-
Save rdohms/892220 to your computer and use it in GitHub Desktop.
Solution to always checking the array elements to avoid PHP notices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Original code | |
$this->setProperty( $data['property'] ); | |
//How it has to be done because array may not contain that value (its optional) | |
$this->setProperty( isset($data['property'])? $data['property'] : null ); | |
/* | |
* Question is: Is there a cleaner way of doing this, if so, how? | |
* | |
* Second question, is: would the code below (create a native php function) make sense as a good solution? | |
*/ | |
$this->setProperty( array_read('property', $data ); | |
// In this case the C code behind this would check for presence of the key and return null if not present | |
// Another solution is to create a SPL function in PHP format to do this | |
//Thanks |
Maybe something like:
$this->setProperty(array_shift((array_slice($data, ($i = array_search('property', array_keys($data))) && !!$i ? $i : count($data), 1))));
There was an PHP RFC for a new operator called "issetor" that does exactly that. Can't show you that 'cause PHP Wiki is on maintenance, but it was something like this:
$this->setProperty( issetor($data['property'], null) );
I think the second parameters default value was false instead of null. Anyway, that operator was rejected. I always use:
$this->setProperty(isset($ data ['property'])? $data['property'] : null);
Patch in the works.
Thanks @davidcoallier
Having the ternary operator execute a "isset" internally would be a great addition to the language, looking forward to it.
btw @alganet .. that has to be the ugliest operator name in the history of programming... :D
@rdohms agreed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rdohms Hello!
I think creating a native function to perform this task could "clean up " your code, but difficult reading software.
To me, your solution seems to be the cleanest. I would not use another. :)
$ this-> setProperty (isset ($ data ['property'])? $ data ['property']: null);