PHP - Use everything from 1st array, remove duplicates from 2nd? - php

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!

For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });

If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}

If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

Related

How to filter array php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to get the bottom values of an array with a single condition as below :
Get all numeric values until the next value is a string then stop the instruction, and leave all other values even if they are numeric
<? php $data= [1,2,3,'web',4,5,6,'web',7,8,9]; ?>
The output will be : 7,8,9
We can try first filtering to find the first non numeric entry. Then, subset the array starting with this index. Finally, filter the subset again to remove all non numeric elements.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$sub_data = array_filter($data, function($item) { return !is_numeric($item); });
$index = array_search(current($sub_data), $data);
$sub_data = array_slice($data, $index);
$sub_data = array_filter($sub_data, function($item) { return is_numeric($item); });
print_r($sub_data);
This prints:
Array
(
[1] => 4
[2] => 5
[3] => 6
[5] => 7
[6] => 8
[7] => 9
)
i don't know if there a specific function for it but i got the same result with this
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
foreach ($data as $key => $value) {
if($value=="web"){
$x =$key;
}
}
$data = array_slice($data,$x);
print_r($data);
Output:
Array ( [0] => web [1] => 7 [2] => 8 [3] => 9 )
You can use array_reverse to get values from the array with elements in reverse order.
$reversed = array_reverse($data);
and then parse the array to stop where it gets a string
foreach($reversed as $value) {
if(is_string($value)) {
break;
}
$output[] = $value;
}
//print_r($output); // to print the output array. This will return the values like 9, 8, 7
// do a reverse again to get the values in the format you want.
$final= array_reverse($output);
print_r($final); // to print the final array. This will return the values like 7, 8, 9
Here is a DEMO
You can just pop values off the end until you get to something that isn't an int.
while (is_int($n = array_pop($data))) {
$result[] = $n;
}
This will modify the data array, so if you need to keep the original values, then do this with a copy.
The test you'll want depends on whether your example data is representative and all the numeric values you want in the array are of type int, or perhaps some might be numeric strings.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$result = [];
for($i = count($data)-1; $i >= 0; $i++) {
// If some of the values you want might be numeric strings
// (e.g. "7") or decimals (e.g. 1.5), use this
if(!is_numeric($data[$i])) {
break;
}
// If your values will only be integer type, use this
if(!is_int($data[$i])) {
break;
}
array_unshift($result,$data[$i]);
}
// If you want the results in original order
print_r($result); // Output: [7,8,9]
// If you want the results inverted
$result = array_reverse($result);
print_r($result); // Output: [9,8,7]
Try this, here i am storing values in to an array $newArray if value is integer. if string found in value just reset the array $newArray
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value)){
$newArray[] = $value;
}
else{
$newArray = array(); // reset if not integer
}
}
echo "<pre>";
print_r($newArray);
?>
DEMO
Result:
Array
(
[0] => 7
[1] => 8
[2] => 9
)
Now, you can use implode() for comma separated result, like:
echo implode(",",$newArray); // 7,8,9
Edit: (08-07-2019)
If Example:
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
Code:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
$newArray = array(); // resultant array
end($data);
$keyLast = key($data); // fetches the key of the element pointed to by the internal pointer
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
else{
if($keyLast === $key) { // if last key is string overwrite the previous array.
$newArray = $newArray;
}
else{
$newArray = array(); // reset if not integer
}
}
}
echo "<pre>";
print_r($newArray);
?>
Edit:
It's better to store all integer values into an array and then use array_slice() to get let three elements from new integer array like:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web','web','web'];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
}
$lastThreeElement = array_values(array_slice($newArray, -3, 3, true));
echo "<pre>";
print_r($lastThreeElement);
?>

Textarea lines to array using php

I have a php variable that contain value of textarea as below.
Name:Jay
Email:jayviru#demo.com
Contact:9876541230
Now I want this lines to in array as below.
Array
(
[Name] =>Jay
[Email] =>jayviru#demo.com
[Contact] =>9876541230
)
I tried below,but won't worked:-
$test=explode("<br />", $text);
print_r($test);
you can try this code using php built in PHP_EOL but there is little problem about array index so i am fixed it
<?php
$text = 'Name:Jay
Email:jayviru#demo.com
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);
$final_data = array();
foreach ($array_data as $data){
$format_data = explode(':',$data);
$final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);
and output is :
Array
(
[Name] => Jay
[Email] => jayviru#demo.com
[Contact] => 9876541230
)
Easiest way to do :-
$textarea_array = array_map('trim',explode("\n", $textarea_value)); // to remove extra spaces from each value of array
print_r($textarea_array);
$final_array = array();
foreach($textarea_array as $textarea_arr){
$exploded_array = explode(':',$textarea_arr);
$final_array[trim($exploded_array[0])] = trim($exploded_array[1]);
}
print_r($final_array);
Output:- https://eval.in/846556
This also works for me.
$convert_to_array = explode('<br/>', $my_string);
for($i=0; $i < count($convert_to_array ); $i++)
{
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array); ?>
I think you need create 3 input:text, and parse them, because if you write down this value in text area can make a mistake, when write key. Otherwise split a string into an array, and after create new array where key will be odd value and the values will be even values old array

How to find the first, second, third etc numbers of an array

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo

Array_merge unknown amount of arrays as variable variables

Thanks for helping as always.
My code generates arrays in the following format
${'readyformerge' . $b} = $temparraytwo;
Which results in the array names of
$readyformerge1
$readyformerge2
$readyformerge3
etc...
Which works well and we know the value that $b holds is the amount of arrays we need to merge. However I can't quite see how to do this when we won't know prior to running the script how many arrays will be created.
Fundamentally I would like to use the following to grab the result but as you see I can only do this for the amount of results I THINk it will return NOT the actual number of results. Any help?
$outputmultidimensionalevent = array_merge_recursive(${'readyformerge' . $b},${'readyformerge' . $b});
print_r($outputmultidimensionalevent); echo '<br/>';
Your problem is the result of bad design.
Instead of:
${'readyformerge' . $b} = $temparraytwo;
You should do something like this:
$readyformerge[$b] = $temparraytwo;
And then:
$merged = array();
foreach ($readyformerge as $one) {
$merged = array_merge($merged, $one);
}
Thanks, That's pushed me in the right direction.
So currently it's now setup like this:
$z=1;
$readyformergemulti = array();
while ($z <= $i){
array_push($readyformergemulti,${'readyformerge' . $z});
$z++;
}
foreach ($readyformergemulti as $one) {
print_r($one);
echo '<br/>';
$merged = array_merge_recursive($merged, $one);
}
print_r($readyformergemulti); echo '<br/>';
print_r($merged); echo '<br/>';
But unfortunately $merged returns nothing. If you look at the following the first 4 lines are the $readyformerge arrays and the 5th line is the desired result:
Array ( [house] => 2797 )
Array ( [house] => 2829 )
Array ( [house] => 2736 )
Array ( [electronica] => 2763 [house] => 2763 )
Array ( [electronica] => Array (2763) [house] => Array (2763,2797,2892,2736 ) )
Sorry to be a pain, and I KNOW everyone needs to see more code, but with thousands of lines it gets hard to display!
If you can help again that would be great!

Array not populating correctly

I am using the following code to populate an array:
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
postcodeUnknown returns the first row from a mysql query, using a table prefix and an element from an array named postcodes. $postcodes contains strings that should return a different row each time though the loop.
Which I'd expect to create an array similar to:
Array ([0] =>
Array ([0] => some data [1] => more data)
[1] =>
Array ([0] => second row [1] => even more...)
)
But it's not. Instead it's creating a strange array containing the first results over and over until the condition is met, eg:
simplified result of print_r($ref);
Array (
[0] => Array ([0] => some data [1] => more data)
)
Array(
[0] => Array (
[0] => the first arrays content...
[1] => ...repeated over again until the loop ends
)
)
And I'm at a loss to understand why. Anyone know better than me.
Try
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref1[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref2[] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref3[$count][] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
echo "<pre>";
print_r($ref1);
print_r($ref2);
print_r($ref3);
echo "</pre>";
Try that to see if any of those get an output you are looking for.
Uh, add a print to postcodeUnknown and check if its actually passing different postcodes or the same thing all the time?
ie
function postcodeUnkown($a,$b){
echo var_dump($a).var_dump($b);
//the rest
}
Also, why two different variables? ($quantitys and $postcodes).
Also, you might want to replace the while loop with for:
for($i=0;$i<$number;$i++){
$ref[$i] = postcodeUnknown ($prefix, $postcodes[$i]);
}
your variable count should not be a string, try this
$number = count ($quantitys);
$count = 0;
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}

Categories