0
0

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 1 year has passed since last update.

【PHP】配列の中身をintに置き換える

Last updated at Posted at 2021-07-30
<?php

$arr =  [1,2,3,'あああ','00456','123abc',-3,' '];

$arr = array_map('intval', $arr);

var_dump($arr);



function convertArrayValues($array) {
    foreach ($array as $key => $value) {
        if (is_numeric($value)) {
            $array[$key] = (int)$value;
        } else if (is_string($value)) {
            $array[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
        }
    }
    return $array;
}

// 使用例
$array = ['1', '2', 'hello', '3', '<script>alert("xss");</script>','1a',0 ];
$result = convertArrayValues($array);

print_r($result);


function convertArrayValues($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $array[$key] = convertArrayValues($value);
        } else if (is_numeric($value) && $value !== '0') {
            $array[$key] = (int)$value;
        } else if (is_string($value)) {
            $array[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
        }
    }
    return $array;
}

// 使用例
$array = ['1', '2', 'hello', '3', '<script>alert("xss");</script>', '0', ['4', '5', '<img src="x">']];
$result = convertArrayValues($array);

print_r($result);


?>

#出力結果

array(8) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(0)←あああ
  [4]=>
  int(456)←00456
  [5]=>
  int(123)←123abc
  [6]=>
  int(-3)
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?