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?

  • 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 Jun 15 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 Jun 15 at 7:14
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.

  • 1
    I don't see explode() in the code, and there's also the file() function for reading the entire file into an array.. Also, how about using a comma-separated list in the file - 1,2,3,4,5 ? And then do explode( ',', $contents ) .. – Sally CJ Jun 15 at 8:00
  • 1
    Sorry, I meant preg_split(). I wrote the sentence before changing my mind and forgot to go back and edit. But yes, you could use explode with commas, but I felt that separating them with line breaks would be easier to maintain. – Jacob Peattie Jun 15 at 8:18
  • Well, one entry per line does look neater than having many numbers there. :) So, +1. – Sally CJ Jun 15 at 8:40
  • I also think the database would love this kind of job, to store many rows and search it :-) Sounds also like a good candidate for a web service, if many sites need this, in that case the data needs only be modified in one place. – birgire Jun 15 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.