开发者

How do I collect the keys of all true values in an array?

This is slightly modified version of the code in the PHP docs:

http://php.net/manual/en/function.next.php

<?php

$array = array(
    -1 => true,
    0 => false,
    1 => true
);

while ($bet = current($array)) {
    if ($bet == true) {
        echo key($array) . '<br />';
    }
    next($array);
}
?>

This is as close as I could get to what I wanted.

This this echoes "-1", and I DO understand why.

What I开发者_Python百科 want to know is how to modify this code so that it will continue searching for "true" values even after it encounters an false (and not just for an array of 3 values).

I realize this might not be the best way of doing it and I am open to suggestions.

Thanks in advance!!

Trufa


echo join("<br>", array_keys(array_filter($array)));

array_filter returns true values when you don't supply a callback method, array_keys gets you the keys for those values, then prep it for output using join


You could use a combination of array_filter and array_keys:

$array = array(
  -1 => true,
  0 => false,
  1 => true
);

$keys = array_keys(array_filter($array));
echo join("<br />", $keys);

See this in action at http://www.ideone.com/AREmK.

array_keys returns an array containing they keys of the given array. array_filter lets you filter elements out of an array based on a callback function. If no callback is given, as the manual states:

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

Note that this will also filter out values that are falsy. If you want to only filter values that are explicitly false:

function filter_false($val)
{
  return $val !== false; // if $val is not false, it'll be kept
}
$keys = array_keys(array_filter($array, 'filter_false'));


You can loop through the entire array:

foreach ($bet as $key => $value) {
  if ($value == true) echo $key . "<br/>";
}

edit: no?.. hmm.. another method:

while (list($key,$value) = each($bet)) { 
  if ($value) echo $key . "<BR/>";
}


The construct while($bet = current($array)) will only continue looping so long as the current array element evaluates to true. In general while loops imply that you're looping until some condition is met.

If you want to perform an action on every element of an array, you should use a for or foreach loop, which more clearly state your intent to iterate over the entire array:

for($i = 0; $i < count($array); ++$i) {

}

foreach ($array as $key => $value) {

}


foreach ($array as $key => $value) { 
  if ($value == true) echo $key . "<br/>"; 
} 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜