- Forums
- PHP
- How To Add Element To Array In PHP
today i was writing a script in php in which i had a loop evaluate all each string, if the string contained a particular part, i wanted to add the string to an element of the array. so this is how i did it using this code [2104], Last Updated: Mon Jun 24, 2024
Padaki52
Thu Oct 07, 2010
0 Comments
645 Visits
today i was writing a script in php in which i had a loop evaluate all each string, if the string contained a particular part, i wanted to add the string to an element of the array. so this is how i did it using this code
my scenario was that i wanted to get a list of all the files where the php script was ran, after i got a list of all the files, i wanted to check each file which the name 'restricted' on it, like for example, i had these files in my directory:
friendly.php
restricted-colors.php
open.php
restricted-passwords.php
functions.php
as you can see from my list, there are two files which contain the word restricted as their file name. so i wanted to only save these files into an array, so this is the PHP code i used to achieve what i wanted.
if ($handle = opendir('.')) {
$stack = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(strstr($file,'restricted')){
array_push($stack, $file);
}
}
}
closedir($handle);
}
you can get more help about the array_push() function at
http://php.net/manual/en/function.array-push.php