Re: If Statements Array and Notice Undefined Index

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 31 March 2011 15:53, Stuart Dallas <stuart@xxxxxxxx> wrote:

> On Thursday, 31 March 2011 at 15:45, Nicholas Cooper wrote:
> Good day,
> >
> > I have three arrays A, B and C. Anyone of them might not have the 'id'
> key
> > set which will give the Notice "Undefined index: id".
> >
> > I just wanted to know what the correct approach to this problem would be;
> > without making the code overly complicated to read by introducing a
> number
> > of "if isset" statements.
> >
> > if ($arrayA['id'] == $arrayB['id'] || $arrayC['id'] == $arrayB['id']) {
> >
> > }
> >
> > I have notices switched off, but I want to know the right way to do this.
> >  There's probably a number of different right ways to solve this, how
> would
> > you do it?
>
> This is how I handle this...
>
> // Define this function somewhere global
> function ifsetor($array, $key, $default = null)
> {
> return (isset($array[$key]) ? $array[$key] : $default);
> }
>
> if (ifsetor($arrayA, 'id') == ifsetor($arrayB, 'id') || ifsetor($arrayC,
> 'id') == ifsetor($arrayB, 'id'))...
>
> If you need to avoid a match if neither $arrayA nor $arrayB have an id you
> simply pass a different default for each one.
>
> -Stuart
>
> --
> Stuart Dallas
> 3ft9 Ltd
>
> http://3ft9.com/
>
>
>
>
Thank you, that is quiet an elegant solution.

Very little additional code excluding the function and it could also easily
be extended for multi dimensional arrays by changing $key to an array and
looping through each index in turn.

Best Regards

Nicholas

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux