Page 1 of 1

Overwrite array1 with values from array2

Posted: Sun Dec 04, 2005 8:21 am
by ed209
Hi,

Does anyone know of a function that will do this:

Code: Select all

$array1 = array("1","2","3","4","5");

$array2 = array("ONE","","","FOUR","");

Then some magic function, which I hope someone will tell me about, executed here then outputs a new array that combines the two above:

Code: Select all

$new_array would equal "ONE", "2", "3", "FOUR", "5"
The important part about this is that elements from $array2 overwrite their element counterpart in $array1


Thanks, in advance, for any help

Posted: Sun Dec 04, 2005 8:37 am
by William

Code: Select all

<?

$array1 = array("ONE", "", "THREE", "");
$array2 = array("", "TWO", "", "FOUR");

$max = count($array2);

for($number=0;$number<$max;$number++)
{
	if($array2[$number] == "") {
		$array2[$number] = $array1[$number];
	}
}

?>
Okay, there you go! I don't know of a majic function so I just did that. :)

Posted: Sun Dec 04, 2005 9:24 am
by foobar
That's not doing what he wants to achieve. AFAIK, what he wants is a function that will evaluate, for instance, "NINE" as 9 and then do the comparison.

For numbers "ONE" to "TEN":

Code: Select all

<?php

$array1 = array("1","2","3","4","5");
$array2 = array("ONE","","","FOUR","");
$array3 = array();

$numwords = array(
  "ONE" => 1,
  "TWO" => 2,
  "THREE" => 3,
  "FOUR" => 4,
  "FIVE" => 5,
  "SIX" => 6,
  "SEVEN" => 7,
  "EIGHT" => 8,
  "NINE" => 9,
  "TEN" => 10
);

foreach ($array1 as $k => $v) {
  $array3[$k] = ($array1[$k] == $numwords[$array2[$k]]) ? $array2[$k] : $array1[$k];
}

print_r($array3);

?>

Posted: Sun Dec 04, 2005 9:42 am
by ed209
Thanks for the replies, I'm not sure if I explained myself properly. I have written my own function which is similar to one of them posted here.

Code: Select all

for($i=0;$i<count($array1);$i++){
	$new_array[$i] = ($array2[$i] != "") ? $array2[$i] : $array1[$i];
}
The idea is that emelent $i in $array2 will overwrite element $i in $array1 . I just thought that as PHP has so many php functions that there would be one to do this instead of having to loop through.

----------------------------------------------------------------
My original post may have been clearer like this:

Code: Select all

$array1 = array("1","2","3","4","5"); 

$array2 = array("DOG","","","PAPER","");
with the function creating a new array containing:

Code: Select all

"DOG", "2", "3", "PAPER", "5"

Posted: Sun Dec 04, 2005 9:46 am
by foobar
Hm... Well, you should have said so then. Try to make your explanations a little less ambiguous next time. For your own benefit.

Posted: Sun Dec 04, 2005 9:58 am
by ed209
William got it :!: