Skip to content

Instantly share code, notes, and snippets.

@rdohms
Created March 29, 2011 11:55
Show Gist options
  • Save rdohms/892220 to your computer and use it in GitHub Desktop.
Save rdohms/892220 to your computer and use it in GitHub Desktop.
Solution to always checking the array elements to avoid PHP notices
<?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
@alganet
Copy link

alganet commented Mar 29, 2011

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);

@davidcoallier
Copy link

Patch in the works.

@rdohms
Copy link
Author

rdohms commented Mar 29, 2011

Thanks @davidcoallier

Having the ternary operator execute a "isset" internally would be a great addition to the language, looking forward to it.

@rdohms
Copy link
Author

rdohms commented Mar 29, 2011

btw @alganet .. that has to be the ugliest operator name in the history of programming... :D

@alganet
Copy link

alganet commented Mar 29, 2011

@rdohms agreed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment