Reputation: 11
I'm new to PHP
and i'm trying to build a type of generator. I started off with hard coding the different array values. So everything that's between "( )" is what I'm going to store in a text file. However I can't see how I should do it.
Ex. $num = array (0,1,2,3,4,5,6,7,8,9);
The numbers 0-9 is what i want array to get from a textfile instead.
Same with $spec = array ('!','#','%','&','?');
Here is how i've done it now:
<?php
$pass = array();
$verb = array ('Klappa', 'Springande','Bakande', 'Badande',
'Cyklande', 'Jagande', 'Skrattande', 'Flygande', 'Simmande','Gissande');
$num = array (0,1,2,3,4,5,6,7,8,9);
$sub = array ('katt', 'hund','fisk', 'padda', 'lama', 'tiger','panda', 'lejon', 'djur', 'telefon');
$spec = array ('!','#','%','&','?');
$pass[] = $verb[array_rand($verb)];
for($i=0;$i<1;$i++){
$pass[] = $num[array_rand($num)];
}
$pass[] = $sub[array_rand($sub)];
for($i=0;$i<1;$i++){
$pass[] = $spec[array_rand($spec)];
}
//shuffle($pass);
foreach($pass as $p){
$password .= $p;
}
// echo "$password <br>";
?>
I don't want ('!','#','%','&','?');
to be shown in the code, also to be read from a text file. What should I do?
Upvotes: 1
Views: 59
Reputation: 1172
If you're writing to a file, you could:
<?php
foreach(range(0,9) as $number){
$output .= $number . PHP_EOL;
}
file_put_contents('textfile.txt', $output);
?>
which will output to textfile.txt in the following format:
0
1
2
3
4
5
6
7
8
9
to read that back into an array, you can then
<?php
$input = file_get_contents('textfile.txt');
$num = [];
$num = explode(PHP_EOL,$input);
//Take the blank element off the end of the array
array_pop($num);
echo '<pre>';
print_r($num);
echo '</pre>';
?>
which will give you the output
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
to read the numbers you can then call
<?php
foreach($num as $number){
//You can do whatever you want here, but i'm just going to print number
echo $number;
}
?>
which will give you
0123456789
I'm aware there are simpler methods, but doing this way so OP can see what's going on.
Upvotes: 1
Reputation: 4210
What you can do is create your file, and insert the characters you want line by line. You can use this code snippet to read the file and insert your values into an array:
<?php
$handle = @fopen("/file.txt", "r");
//declare your array here
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
//add $buffer to your array.
}
fclose($handle);
}
?>
You may want to look at this as a reference.
Upvotes: 0