Page 1 of 1

array_splice and array_search functions- how to use it?

Posted: Fri Mar 23, 2007 1:53 pm
by rekha_harnoor
Hi I am using php5.

My code is as follows: I want to update the array

Code: Select all

<?php

for($i=0; $i<2; $i++) {
		   
	   $yahoo_info[$i] = array('ProductName' => "ABC" ,
	                       'YahooMinPrice' => "$10");
	                       	                      	                       
}

for($i=0; $i<2;  $i++) {
            foreach ($yahoo_info[$i] as $key => $value) {
 
             if (array_search("ABC", $yahoo_info[$i], true))
                {
 	    $AmazonP = array('AmazonPrice' => "$5");
                    array_splice($yahoo_info[$i], 2, 0, $AmazonP);      
                 }
 
           }
}


for($i=0; $i<2;  $i++) {
	 echo "<hr />\n";
foreach ($yahoo_info[$i] as $key => $value) {
 
 echo $key.'=>'.$value.'<br />';
}
}
?>
I am getting output is as follows:

ProductName=>ABC
YahooMinPrice=>$10
0=>$5
1=>$5

-------------------------------------------------------
ProductName=>ABC
YahooMinPrice=>$10
0=>$5
1=>$5

array_splice($yahoo_info[$i], 2, 0, $Amazon); inserting the record twice because of the loop. How to add it only once ?

I want following output

ProductName=>ABC
YahooMinPrice=>$10
AmazonPrice=>$5

-------------------------------------------------------
ProductName=>ABC
YahooMinPrice=>$10
AmazonPrice=>$5

Posted: Fri Mar 23, 2007 2:10 pm
by feyd
How is for() supposed to be used in this context? foreach() is already a loop.

Posted: Fri Mar 23, 2007 4:41 pm
by RobertGonzalez

Code: Select all

<?php
// This makes the same entry into the array twice
for ($i=0; $i<2; $i++) {
    $yahoo_info[$i] = array('ProductName' => "ABC" , 'YahooMinPrice' => "$10");
}

// Again, looping two times
for ($i=0; $i<2;  $i++) {
    // First iteration of the for loop, let us foreach the yahoo_info array
    // Take note that each member of the array is identical to itself
     foreach ($yahoo_info[$i] as $key => $value) {
        // You could probably use in array or array_key_exists here
        if (array_search("ABC", $yahoo_info[$i], true)) {
            $AmazonP = array('AmazonPrice' => "$5");
            array_splice($yahoo_info[$i], 2, 0, $AmazonP);     
        }
    }
}

// What is with all the loops, I am getting dizzy 
for ($i=0; $i<2;  $i++) {
    echo "<hr />\n";
    foreach ($yahoo_info[$i] as $key => $value) {
        echo $key.'=>'.$value.'<br />';
    }
}
?>