albator
albator

Reputation: 859

Check if all values of keys of multidimentionnal array are numeric?

i'm gona crazy, debuting in php..

I need to check if key value of an multidimentionnal array are all numeric..

a print_r() of my $values_arr give that:

Array ( [coco] => Array ( [0] => 18 [1] => 99 ) [chanel] => 150

I need to check if 18 and 99 and 150 are numeric, i will don't know what will in the array , and this array will not more 2 dimention.

I tryed many things, the last one..:

foreach ( $values_arr as $foo=>$bar ) { 

 if(  !in_array( $foo, $_fields_arr )  || !is_numeric($bar ) ) {

                        echo "NOTGOOD";   

                 } 
                 }




                          ****UPDATE****

new test :Here because chanel isnot int , this exemple should be echo "not goud", but its not the case..

$_fields_arr = array('coco','chanel','other');                                

$ary = array(
  'coco' => array(18, 99),
  'chanel' => 'yu'
);


function allIntValues($o)
{
  if (is_int($o)) return true;
  if (is_array($o)){
    foreach ($o as $k => $v) {
      if (!is_int($v)) return false;
    }
  }
  return true;
}

foreach ($ary as $k => $v) {
  if (!in_array($k, $_fields_arr) || !@allIntValues($v)){

echo "notgood";

 }

  else echo "good";
}

thanks for any help, regards

Upvotes: 0

Views: 190

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

Update:

$ary = Array(
  'coco' => array(18, 99),
  'chanel' => 150
);
$_fields_arr = array('coco', 'chanel');

function allIntValues($o)
{
  if (is_int($o)) return true;
  if (is_array($o)){
    foreach ($o as $k => $v) {
      if (!is_int($v)) return false;
    }
  }
  return true;
}

foreach ($ary as $k => $v) {
  if (in_array($k, $_fields_arr) && @allIntValues($v)){
    // $ary[$k] is no good
  }
}

Assuming you want to test if all values are numeric (despite how deep the value's nested):

function is_numeric_array($ary)
{
  foreach ($ary as $k => $v)
  {
    if (is_array($v))
    {
      if (!is_numeric_array($v))
        return false;
    }
    else if (!is_numeric($v))
      return false;
  }
  return true;
}

That will (recursively) check the array and make sure every value is numeric within the array.

array(1,2,3) // true
array('foo','bar','baz') // false ('foo', 'bar' & 'baz')
array(1,2,array(3,4)) // true
array(array(1,'foo'),2,3) // false (foo)
array("1,", "2.0", "+0123.45e6") // true

Upvotes: 1

Manolo
Manolo

Reputation: 26370

You are using the value instead of the key:

if(  !in_array( $bar, $_fields_arr )  || !is_numeric($foo ) ) {

Upvotes: 0

Related Questions