Say I have an array that looks like this:

Code:
$array = array(0,1,2,3);


Is it possible to have a default array value so that if you attempt to access a value outside of the array, it returns an error message?


This code would return the default value since the array element 10 doesn't exist.

Code:
echo $array[10];


Code:
// Default value to return
echo "The value doesn't exist.";
You could implement it like this:


Code:
$default_array_dne = "[MISSING VALUE]";

function StrictArrayGet($array,$key) {
    global $default_array_dne;
    return array_key_exists($key,$array)?$array[$key]:$default_array_dne;
}
Ok, I see how that would work, but is there such thing as a default array though, kind of like switch/case?

If not, I guess that this would be the best solution.
kpa4941 wrote:
Ok, I see how that would work, but is there such thing as a default array though, kind of like switch/case?

If not, I guess that this would be the best solution.
You could restructure it as a conditional instead of a function, but I don't think PHP has a more elegant way to do this (at least that I know of).
Alright well thanks for the help. It would be nice if PHP had something like that in the future.

I think that I am going to go with your function.
kpa4941 wrote:
Alright well thanks for the help. It would be nice if PHP had something like that in the future.

I think that I am going to go with your function.
Excellent, I hope that it serves you well. You should suggest this to the PHP developers!
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement