PHP – array_keys, array_fill_keys, key 用法

array_keys, array_fill_keys, key 用法

PHP basic function,array_keys, array_fill_keys, key,有關陣列的應用,也用簡單的舉例來介紹吧!

  • array_keys
  • array_fill_keys
  • key

array_keys

array_keys – 陣列中所有鍵名的一個新陣列
array array_keys ( array $array [, mixed $search_value [, bool $strict = FALSE ]] )

$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

Array
(
  [0] => 0
  [1] => color
)

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

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

$array = array('color' => array('blue', 'red', 'green'),
'size' => array('small', 'medium', 'large'));
print_r(array_keys($array));

Array
(
  [0] => color
  [1] => size
)


array_fill_keys

array_fill_keys – 指定的鍵和值填充陣列
array array_fill_keys ( array $keys , mixed $value )

$keys = array('omg', 5, 10, 'charlie');
$a = array_fill_keys($keys, 'banana');
print_r($a);

Array
(
  [omg] => banana
  [5] => banana
  [10] => banana
  [charlie] => banana
)


key

key – 從陣列中取得鍵名
mixed key ( array $array )

$array = [
  'fruit1' => 'apple',
  'fruit2' => 'orange',
  'fruit3' => 'grape',
  'fruit4' => 'apple',
  'fruit5' => 'apple'
];
while ($fruit_name = current($array)){
  if ($fruit_name == 'apple') {
    echo key($array).'<br />';
  }
  next($array);
}

fruit1
fruit4
fruit5

$people = array('Bill', 'Steve', 'Mark', 'David');
echo key($people);

0

一起討論吧