开发者

There is a way to get all keys of the array?

I want to get all keys of the array an compare each key to number, somthing like that:

array(
[0] => 7
[1] => 8
[2] => 4
[3] => 6
)

if (6 != EACH KEY OF ARRAY) {
    so...
}

The condition wont show becaus开发者_运维知识库e there is [3] => 6 and the key 6 = 6 of course.

There is a function to do it? somthing else?


.

foreach($array as $key => $val)
{
  if (6 != $key) {
   // so...
  }
}

Example:

$array = array(7, 8, 4, 6);

foreach($array as $key => $val)
{
  if (6 != $key) {
   echo '6 is not equal to ' . $key . '<br />';
  }
  else {
   echo '6 is equal to ' . $key . '<br />';
  }
}

Result:

6 is not equal to 7
6 is not equal to 8
6 is not equal to 4
6 is equal to 6

If however, you want to check if the value of 6 is present in the array, use in_array like this:

if (in_array(6, $array)) {
  // 6 is present in the array
}


You want the array_keys functions, most likely:

<?php
$array = array(7,8,4,6);

// Keys is an array of the keys from $array - [0,1,2,3]
$keys = array_keys($array);

print_r($keys);
?>

The output of that print_r would be:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)

(Note the original keys are the values of the new array.)

You then want to check if the value you are looking for is in the array using in_array:

<?php
echo in_array(6, $keys) // FALSE
?>


If you just want to see if a key is present in the array, this is the fastest method:

$key = 6; // for example
if(isset($myArray[$key]))
{
    echo "the key $key is used in the array";
}


I'm not sure if I understand what you're asking but one of these will probably fit you:

Get just the keys:

print_r(array_keys($array));

Exchanges keys with values:

print_r(array_flip($array));

foreach ($array as $key => $value)
{
    var_dump($key, $value);
}


if(!in_array(6)) {
}

Yes I know OP asks about keys, but from his example it seems he wants values.


you can't have more than one of the same key so there is no need to loop through the entire array just write code to look for it. you could do this:

$arr = Array('1'=>'a','3'=>'b','6'=>'c');

if (array_key_exists('6',$arr))
{
    echo 'value of 6 = ' . $arr['6'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜