Page 1 of 1

How to append to an existing array?

Posted: Thu Sep 12, 2002 10:24 pm
by MAsKrA
Ok so I read my file into memory, then search for any line that starts with Counter and replace it with my new line. Works perfect. Now how in the code below can I specify that if I dont find any lines with that start with Counter then Append it to the end of the file?

Thanks in advance.... again :twisted:

Code: Select all

elseif (file_exists($htaccess)) {
		//Read it in to and array
		$file = file("$htaccess");
		$count = 1;
		$maxval = count($file);
		while ( $count <= $maxval )&#123;
		//search for any line that starts with Counter
		if ( ereg("Counter",$file&#1111;$count]) )&#123;
		$file&#1111;$count] = "$counter_syntax";
		&#125;
        else 
        &#123;
        //I need to append $counter_syntax How? 
        &#125;
		$count++;
		&#125;
		
		// To write to the file incase we found a line with Counter 
		$a1 = fopen("$htaccess", "w+");
		flock($a1,2); 
		foreach ($file as $key)&#123; 
		$fw = fwrite($a1, $key); 
		&#125;
		//And we close again 
		fclose($a1);

Posted: Fri Sep 13, 2002 3:51 am
by volka
try this

Code: Select all

&lt;?php $array = array('marry');
$array&#1111;] = 'had';
$array&#1111;] = 'a';
$array&#1111;] = 'little';
$array&#1111;] = 'lamb';

print_r($array);
?&gt;

Posted: Fri Sep 13, 2002 1:07 pm
by MAsKrA
Ah ha got it again. All I did was set a variable called $success = "Yes"; if the line that started with my search string was found, then outside my loop, I array_push my new line only if $success was flase. Thanks again for the help:

Code: Select all

if ( ereg("Counter",$file&#1111;$count]) )
                                &#123;
                                        $file&#1111;$count] = "$counter_syntax";
                                        $success = "Yes";
                                &#125;
                $count++;
                &#125;
                if ( $success != Yes )
                &#123;
                        // I need to append >   $counter_syntax
                        array_push($file, $counter_syntax);
                &#125;
:twisted: