最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Best way to use a large array in function

programmeradmin2浏览0评论

I need to define an array which has more than 15000 values in the wordpress functions file:

$validpin = array(110019,111222,112233);

I have written only 3 values to explain but the actual array will have more than 15000 values. How should I go about doing, as writing 15000 values is making the functions file very large?

I need to define an array which has more than 15000 values in the wordpress functions file:

$validpin = array(110019,111222,112233);

I have written only 3 values to explain but the actual array will have more than 15000 values. How should I go about doing, as writing 15000 values is making the functions file very large?

Share Improve this question asked Jun 15, 2019 at 7:03 dc09dc09 1952 silver badges14 bronze badges 2
  • What are you going to do with the values? Your variable name suggest it's "valid pins", but surely there's a rule you could implement, rather than just listing 15000 values. – Jacob Peattie Commented Jun 15, 2019 at 7:11
  • The values are postcodes on which I want to restrict certain payment methods, there's no pattern as such as post codes are random. I would need to list post codes individually, need the bast possible way to do so. – dc09 Commented Jun 15, 2019 at 7:14
Add a comment  | 

1 Answer 1

Reset to default 2

If it's just a list of numbers, I'd suggest just saving them in a text file, with a number on each line.

110019
111222
112233

Then when you need the file, read its contents with PHP, and use preg_split() to turn it into an array:

$file_path     = plugin_dir_path( 'postcodes.txt', __FILE__ ); // Or wherever you've placed it.
$file_contents = file_get_contents( $file_path );
$postcodes     = preg_split( "/\r\n|\n|\r/", $file_contents );

if ( in_array( $postcode, $postcodes ) ) {

}

That preg_split() method for splitting text based on newlines is taken from here.

发布评论

评论列表(0)

  1. 暂无评论