0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPビルトイン関数~配列に関する関数~

Posted at

学習記録

#前提条件
・PHP version 5.4

#配列に関するの関数
・array_unshift
・array_push
・array_shift
・array_pop
・array_slice
・array_splice

##array_unshift
配列の先頭に追加する

書式
$変数=array_unshift(配列, 追加したい要素);
//追加したい要素は何個でも可能
builtin.php
$input = [30, 40, 50];
array_unshift($input, 10, 20);
print_r($input);
//結果 : Array ( [0] => 10 
//        [1] => 20 
//        [2] => 30 
//        [3] => 40 
//        [4] => 50) 

##array_push
配列の末尾に追加する

書式
$変数=array_push(配列, 追加したい要素);
//追加したい要素は何個でも可能
builtin.php
$input = [30, 40, 50];
array_push($input, 60, 70);
print_r($input);
//結果 : Array ( [0] => 30 
//        [1] => 40 
//        [2] => 50 
//        [3] => 60 
//        [4] => 70) 

##array_shift
配列の先頭を削除する

書式
$変数=array_shift(配列);
builtin.php
$input = [30, 40, 50];
array_shift($input);
print_r($input);
//結果 : Array ( [0] => 40 
//        [1] => 50 ) 

##array_pop
配列の末尾を削除する

書式
$変数=array_pop(配列);
builtin.php
$input = [30, 40, 50];
array_pop($input);
print_r($input);
//結果 : Array ( [0] => 30 
//        [1] => 40 ) 

##array_slice
配列から切り出したい位置の先頭から何個分か切り出す

書式
$変数=array_slice(配列, 切り出したい要素の先頭, 個数);
builtin.php
$input = [30, 40, 50, 60, 70, 80];
$a = array_slice($input, 2, 3);
$b = array_slice($scores, 2);
$c = array_slice($scores, -2);
print_r($a);
//結果 : Array ( [0] => 50 
//               [1] => 60 
//               [2] => 70 ) 

print_r($b);
//結果 : Array ( [0] => 50 
//               [1] => 60 
//               [2] => 70 ) 

print_r($c);
//結果 : Array ( [0] => 60 
//               [1] => 70 )

##array_splice
配列のある位置から個数分排除

書式
$変数=array_splice(配列, 切り出したい要素の先頭, 個数);
builtin.php
$input = [30, 40, 50, 60, 70, 80];
array_splice($input, 2, 3);
print_r($input);
//結果 : Array ( [0] => 30 
//               [1] => 40 
//               [2] => 80 ) 

//追加することもできる
array_splice($input, 2, 3, 100);
print_r($input);
//結果 : Array ( [0] => 30 
//               [1] => 40 
//               [2] => 100 
//               [3] => 80 ) 


//個数を0にすると削除せずに置換する
$scores = [30, 40, 50, 60, 70, 80];
array_splice($scores, 2, 0, [100, 101]);
print_r($scores);
//結果 : Array ( [0] => 30 
//               [1] => 40 
//               [2] => 100 
//               [3] => 101 
//               [4] => 50 
//               [5] => 60 
//               [6] => 70 
//               [7] => 80 )
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?