array_splice and array_search functions- how to use it?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rekha_harnoor
Forum Commoner
Posts: 32
Joined: Mon Feb 19, 2007 3:17 am

array_splice and array_search functions- how to use it?

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

How is for() supposed to be used in this context? foreach() is already a loop.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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 />';
    }
}
?>
Post Reply