PHP - Array_merge / Array_diff Question
I am trying to understand why the following code outputs the value of 4 (it is part of a PHP quiz question). I know that array_diff will compare one array with another and return the result but I just don't understand what is going on with the code below:
Code: [Select] <?php $a = array(1,2,4,8); $b = array(0,2,4,6,8,10); echo count (array_merge(array_diff($a, $b), array_diff($b, $a))); //prints 4 ?> Would someone be able to walk me through it? Similar TutorialsI have two strings: $string = shell_exec('reg.bat '.$arg); //returns word\0word\0word $stringA = "$string"; $stringB = "word,other,word2,other2"; $array1 = explode('\0', $stringA); $array2 = explode(',', $stringB); $result = array_diff($array1, $array2); I can use array_diff to find the differences, but the last word in $array1 shows up as not in both strings even though it is because of the \0 delimiter. How can I include the last word as well? I have a very simple script which should be working with no problems. I have 2 arrays, and I'm simply trying to array_diff them to get the results from array1 which are not present in array2. $scrubbed = array_diff($numbers, $dnc); print_r($numbers); print_r($dnc); print_r($scrubbed); The results: Code: [Select] Array ( [0] => 3042476001 [1] => 3042476002 [2] => 3042476003 [3] => 3042476004 [4] => 3042476005 [5] => 3042476006 [6] => 3042476007 [7] => 3042476008 [8] => 3042476009 [9] => 3042476010 [10] => 3042476011 [11] => 3042476012 [12] => 3042476013 [13] => 3042476014 [14] => 3047655291 [15] => 3047281328 ) Array ( [0] => 3042476068 [1] => 3047281328 [2] => 3047652846 [3] => 3047652982 [4] => 3047655291 [5] => 3047655398 [6] => 3047655458 [7] => 3047655719 [8] => 3047657562 [9] => 3047657747 ) Array ( [0] => 3042476001 [1] => 3042476002 [2] => 3042476003 [3] => 3042476004 [4] => 3042476005 [5] => 3042476006 [6] => 3042476007 [7] => 3042476008 [8] => 3042476009 [9] => 3042476010 [10] => 3042476011 [11] => 3042476012 [12] => 3042476013 [13] => 3042476014 [14] => 3047655291 [15] => 3047281328 ) Now, $numbers is drawn from a single column .csv file, and $dnc is concatenated from anywhere between 1 and 3 mysql database queries (there are 3 seperate Do Not Call lists). There are 2 numbers from $numbers which should have been removed, but are not. I have tried intval() to make sure all types are the same using array_walk(), and I have also tried to trim() with array_walk() in case there were any extra characters not showing up on the print_r. I am at quite a loss here Someone help? EDIT: I have also tried to use the following work around functions function array_diff_alt($array1, $array2){ $result = array(); foreach ($array1 as $value){ if (!in_array($value, $array2)){ $result[] = $value; } } return $result; } function array_diff_alt($a, $b) { $map = $out = array(); foreach($a as $val) $map[$val] = 1; foreach($b as $val) unset($map[$val]); return array_keys($map); } function array_diff_alt($a, $b) { $result = array(); foreach ($a as $avalue){ foreach ($b as $bvalue){ if ($avalue != $bvalue){ $result[] = $avalue; break; } } } return $result; } Why is this not working??? If $adsused prints out: 1, 5, 6, 7, while ($tarray=mysql_fetch_array($admintotadsq)){ $adsused .= $tarray['adnr'].', '; } $array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); $array2 = array($adsused); $diff = array_diff($array1, $array2); print_r($diff); print_r($diff); prints out: Array ( => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 [10] => 11 [11] => 12 [12] => 13 [13] => 14 [14] => 15 [15] => 16 [16] => 17 [17] => 18 [18] => 19 [19] => 20 ) What am I doing wrong? So I have two arrays (soon to be multiple). What I want to do is merge all those arrays into one, so that I can then proceed to inserting the data all together. Here's an example of what array1 looks like. Code: [Select] Array ( [0] => Array ( [name] => samus1 [forum] => phpfreaks.com ) [1] => Array ( [name] => samus2 [forum] => stackoverflow.com ) ) And array2: Code: [Select] Array ( [0] => Array ( [posts] => 25 ) [1] => Array ( [posts] => 2500 ) ) I then tried to do: Code: [Select] print_r(array_merge($array1, $array2)); Yet it prints nothing? When I print the other arrays individually the values are shown, but after I use array_merge() it doesn't. Anyone got an idea why? Hi Guys, Been a while since I've done this and I cant seem to get it right. I am using an array to create a dropdown menu. The first array is all options, and the second array is the selected option. Here is the code I am using to merge the arrays. //create the dropdown $possible_pages = $this->admin_model->page_dropdown(); $current_page = $this->admin_model->current_page_dropdown($page_id); $data['pages_dropdown'] = array_merge($current_page, $possible_pages); The result I am getting seems to be reseting the keys in the array, which will not work as intended. Please point me in the right direction to get this array to look as intended the in the example below. I would like the array to look like... Array ([8] => VPO's [7] => CPO's [8] => VPO's) Here are the arrays... Array ( [7] => CPO's [8] => VPO's ) Array ( [8] => VPO's ) This is the result I am getting now. Array ( [0] => VPO's [1] => CPO's [2] => VPO's ) Hi, I failed to merge arrays. This is the case. $arraylength= 2; for($i=0;$i<$arraylength;$i++){ $vars[] = array( $key1[$i] => $value1[$i], $key2[$i] => $avalue2[$i], $key3[$i] => $avalue3[$i]); } print_r($vars); I got then, for example, this output Code: [Select] Array( [0] => Array ( [key0] => value1, [key0] => value1, [key2] => value2 ) [1] => Array ( [key10] => value10, [key11] => value11, [key12] => value12 ) ) Then I need to merge those two arrays. It should be like array_merge($vars[0],$vars[1]);, but how can i merge more arrays? Thank you in advanced, ayok I have two arrays of strings, one is read in from a file, the other is collected on a previous page using js and passed with a form through $_POST. The array from the file I label $oldImages and the array from the previous page I label $newImages (each is a list of image URLs). I need to compare the two and add them together so that there are no duplicate entries. I'm using array_diff() on them and the result I'm getting includes one entry that is in both arrays. I've tried different ways of reading the file, none of them seem to make any difference in the results. I've been printing the arrays with print_r() to have a look at the contents of the arrays and I decided to use implode() and explode(), and str_replace() to try to remove any irregularities that might be in the objects somehow which I'm not seeing. I'm not a PHP programmer, BTW. Here is some code. I've also attached a screenshot for you--link at the bottom. Code: [Select] <body> <?php $file = file("image_list.txt") or exit("Unable to open file!"); $oldImages = implode($file); $oldImages = str_replace(" ", "", $oldImages); $oldImages = explode("\n", $oldImages); $newImages = implode($_POST); $newImages = str_replace(" ", "", $newImages); $newImages = explode("\n", $newImages); $newAdditions = array_diff($newImages, $oldImages); print_r($newImages); echo '<br><br>'; print_r($oldImages); echo ' <form method="post" action="#"> New Images<br> <textarea id="displayText" rows="5" cols="105" wrap="off" name="existing"> '; foreach($newImages as $key => $entry) echo $entry; //echo $newImages; echo ' </textarea> <br> Stored Images<br> <textarea id="newText" rows="5" cols="105" wrap="off" name="new"> '; foreach($oldImages as $key => $entry) echo $entry; //echo $oldImages; echo ' </textarea> <input type="submit" class="button" value="Submit"><br> </form> Newly Generated Image List<br> <textarea id="newText" rows="30" cols="105" wrap="off" name="new"> '; foreach($newAdditions as $key => $entry) echo $entry; echo ' </textarea> '; ?> <div class="clear"></div> </body> Here is the code from the previous page which produces the array that is stored in $_POST. What you can't see in this code is the javascript functions toggleEntry() and displayList(). All they do is handle the addition and removal of image URL strings to/from the textarea object, which I do using document.getElementById('text').InnerHTML=$myList, where $myList has strings being added or removed to/from it. Code: [Select] <script type="text/javascript" src="/js/user_selection_list_builder.js"></script> <script type="text/javascript"> function toggleAndDisplay(key) { toggleEntry(key); displayList(); } </script> </head> <body> <form method="post" action="add_images2.php"> Selected Images<br> <textarea id="displayText" rows="10" cols="90" wrap="off" name="comments"> </textarea> <input type="submit" class="button" value="Submit"> </form> <div class="clear"></div> <?php $i = 2; include 'simple_html_dom.php'; if($i===1) $html = file_get_html('lookbook-source.htm'); elseif($i===2) $html = file_get_html('http://lookbook.nu/preference/look-list-gender/girls'); elseif($i===3) $html = file_get_html('http://lookbook.nu/new'); // Match all div tags of the class 'look_photo'. foreach($html->find('div[class=look_photo]') as $key => $entry) { echo " <div class='imgBox'> <a href='javascript:toggleAndDisplay(".$key.")'><img id='".$key."' src='".$entry->last_child()->last_child()->src."'></a> </div> "; } ?> </body> Here's the code I am working with: Code: [Select] <?php echo " cupcakes, ".$_SESSION['delcol'].", with the following toppings: "; $array1 = $_SESSION['notopping']; $array2 = $_SESSION['topping']; $resultam = array_merge($array1, $array2); $last = array_pop($resultam); $topping = implode(', ', $resultam) .' & ' .$last; echo $topping; ?> I have two arrays which I want to join together, if $_SESSION['notopping'] this can contain 1 - 6. $_SESSION['topping'] can contain vanilla, chocolate or chocolate orange. What I'm trying to achieve is to merge the arrays so that it shows like 1 x Vanilla, 2 x Chocolate & 3 x Choc Orange. As it was it was formatted so it showed just the toppings (with commas and ampersand). The code above appears as this : 1, 2, 3, Vanilla, Chocolate & Choc Orange - the two arrays are separated out, what am I missing here? Thanks! I want to merge some arrays as Code: [Select] $mixing = array_merge($mixedresult1, $mixedresult2, $mixedresult3);but the arrays can be empty sometimes. In this case, I will get an error for the empty array as Code: [Select] PHP Warning: array_merge() [<a href='function.array-merge'>function.array-merge</a>]: Argument #1 is not an arrayHow I can avoid this error by omitting empty arrays? when in a form, I wish to build a conditional that if the response to a radio button is a value of 2 (female), it will display an input requesting for users maiden name. If not 2 goes to the next input statement. Here is code I was experimenting with: <html> <body> <form action="" name="test" method='POST'> <input type="radio" id="sex" value=1 checked><label>Male</label> <input type="radio" id="sex" value=2><label>Femaleale</label> <?php $result = "value"; if ($result == 2) echo "<input type='int' id='gradYear' size='3' required>"; else echo "Not a female!" ?> <input type="submit" value="GO"> </form> </body> </html> The code passes debug, however, Not a Female is displayed. My question is - Can I do this and if so, what value do I test against id='sex' or value. I tried each one but gave the same results. I realize that $_POST[sex] would be used after the submit button is clicked. But this has me stumped. Thanks for the assis in advance. Hey, I have a while that shows the rows(duh). What i want to do is: show 3 rows then echo float left or clear both. So basically 3 at a time, but it shows all the rows in a nice order. Can someone do this? Cheers. I am trying something simple, creating some horses and making them race using OOP, creating them is easy, how can i find out which one "won" based on the highest total. Here is what i got so far Code: [Select] <?php class Horse { public $strength; public $speed; public $agility; public function create($name,$age,$odds){ $this->name=$name; $this->odds=$odds; $this->strength=(rand(50,200) * $this->odds - $this->age); $this->speed=(rand(100,400) * $this->odds - $this->age); $this->agility=(rand(150,250) * $this->odds - $this->age); $all=array(0=>"$this->strength",1=>"$this->speed",2=>"$this->agility"); echo "<b>$this->name</b> has a strength of <b>$this->strength</b>, a speed of <b>$this->speed</b> and agility at <b>$this->agility</b>. --- <b>".array_sum($all)."</b><br>"; } } $mix=rand(2,6); $a=new Horse; $a->create("Dave", 2, $mix); $a->create("Dude", 3, $mix); $a->create("Evan", 3, $mix); $a->create("Jill", 15, $mix); $a->create("Flex", 10, $mix); ?> I cant figure out a way to find out who had the highest total, i would love to know what i am doing wrong. i am looking for a way to write a php script to pull information from a html table and put that information in to the databases does any one have any idea who to do this Looking at a forum like PHPbb or similar. Wondering if anyone can tell me how the system (or scripts) manages to pull all the user information when viewing a thread without a massive amount of database calls? For example, lets say 1 thread has 10 different users associated to it. When you view the thread, on the left you see the username, their avatar, when the membership was created, maybe even the users level or amount of interaction. So, for each thread view (or page view) does the program do a SQL Select back to the user database for each user's information or is the users information being pulled from cache somewhere? Any insight into the logistics is greatly appreciated! I am trying to make my database search only search where private = '$priiv'(Usually 0,1, or 2) but it does not work Code: [Select] $query_search = "SELECT * FROM users WHERE username LIKE '%$idea%' OR fname LIKE '%$idea%' OR lname LIKE '%$idea%' OR tags LIKE '%$idea%' AND private = '$priiv'"; What am i doing wrong? hi php people, I am wondering will if the code below will work when I call $C->getafoo() will I get foo; I keep getting an error at this point return $this->A->a(); saying the method is not there Code: [Select] class A{ public function a(){ return "foo"; } } class B { public $A; function __construct($A) { $this->A = $A; } public function geta(){ return $this->A->a(); } } class C extends B{ public function getafoo(){ return geta(); } } $C = new C(new A()); echo $C->getafoo(); i have took a test that i think it has some errors: can you please confirm or infirm that A is the right answer? Question: The default value for __FILE__ is _______________________________. A. the complete path of the currently executing script B. the relative path of the currently executing script C. a magical constant; it does not have a default value D. the complete path of the previous executed script E. the relative path of the previous executed script Correct Answer: C User Answer: A Explanation: The PHP engine stores the full path and filename of the currently executing script within the __FILE__ constant. Just get started with OO in PHP. If I create an object while on one page and then call another page, can I still access that first object, or is it destroyed when the second page is called? For example, if I have on page1.php: Code: [Select] $obj = new $MyObject(); and then call page2.php, is it possible to still access $obj while on that page? I have been away from PHP for a long time and I was looking over my old scripts. I did PHP OOP at one time and I used a paticular method to connect all my methods up and load them. I have been looking at other peoples code and when I look at my code it does not even feel like OOP, I want to know how to you link all the methods (or is it called functions?) in a class up and return them? I use to do this: Code: [Select] <?php class quickFUNC { function note_pad() { // code for notepad } function quickAdminFunc() { // code for admin func $this->note_pad(); } } $quickFUNC = new quickFUNC; if(isset($_GET['id'])) { $act = $_GET['id']; } else { $act = NULL; } switch ($act) { case 1: //some random code to launch case 1 break; default: $quickFUNC ->quickAdminFunc(); ?> This was my code back in the days, as you can see the notepad was called in the admin function then made the admin function default in the case switch. I looked at all my script and the all are layed out like this :S.. Can I get some help please, thank you. I'm trying to secure my login system as much as possible from SQL injections and other attacks. I know that by using mysql_real_escape_string() you can prevent that and I'm using that on for example the username input, but I would like to know if you hash the password before you send it to the database with MD5, do you still need to use mysql_real_escape_string()? A very quick and simple example: Code: [Select] <?php $un = $_POST['username']; $pass = $_POST['password']; $pass = md5($pass); mysql_query("SELECT * FROM users WHERE password='$pass' AND username='$un'"); ?> If someone wrote a possible SQL query in the password input, wouldn't that be rendered useless as the md5 will hash it before sending it and therefor "hide" it? Or is there any other reason you wouldn't want people to use sertain characters/symbols in their passwords? |