I am using this piece of code to compare two php arrays, I got all matched items rightly but unfortunately i am not succeeding in getting non matched items. Here is my code.
<?php
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',',$cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
$m=0;
$nm=0;
for($i = 0; $i< count($parts1); $i++)
{
for($j = 0; $j< count($parts2); $j++)
{
if($parts1[$i] == $parts2[$j])
{
$m++;
$p[] = $parts1[$i];
}
else{
$nm++;
$q[] = $parts1[$i];
}
}
}
echo $m;
echo "<br />";
echo $nm;
echo "<br />";
print_r($p);
echo "<br />";
print_r($q);
?>
Can someone help me sorting out this problem, As i dont want to use builtin array comparison functions.
I would use the internal functions for this (if I understood your question)
Matched:
$matched = array_intersect($parts1, $parts2);
Difference:
$difference = array_diff($parts1, $parts2);
Or in your world of for loops:
<?php
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',', $cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
$matched = $not_matched = array();
for ($i = 0; $i < count($parts1); $i++)
{
if (in_array($parts1[$i], $parts2))
{
$matched[] = $parts1[$i];
}
else
{
$not_matched[] = $parts1[$i];
}
}
print_r($matched);
print_r($not_matched);
?>
I have been working on adding another loop instead of using in_array() but I'm not going to update my answer for two reasons.
1) Use
$matched = array_intersect($parts1, $parts2);
$difference = array_diff($parts1, $parts2);
Writing this much code instead of two lines is against my religion.
2) The only reason to create this amount of code stricly not using array_* or in_array functions must be for some quiz or test, which I want to enter and win.
Use array_intersect, array_diff and array_merge
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',',$cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
print_r(array_intersect($parts1, $parts2));
print_r(array_merge(array_diff($parts1, $parts2), array_diff($parts2, $parts1)));
Array ( [0] => BLUEBERRIES [2] => CORNSTARCH [3] => SUGAR ) Array ( [0] => ABC [1] => WATER )
You are doing the cartesian product of the two arrays.
If you find that $parts1[$i] == $parts2[$j], it is correct to add $parts1[$i] to $p, but the opposite assumption (if they are different then add to $q) is wrong.
You should start with all elements in $q and when you have a match, add it to $p and remove it from $q.
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
This is the php library function.
Related
I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo
I want to combine three arrays into one
I am expecting like output are using array_combine or array_merge
Likes
friends,
usa,
usa2,
..,
..,
so.on..,
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = $array1+$array2+$array3;
echo "<pre>";
print_r($output);
echo "</pre>";
But here i am getting output as
likes,
friends,
USA
In PHP 5.6+ You can also use ... when calling functions to unpack an array or
Traversable variable or literal into the argument list:
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";
demo
check this out custom function for array push
<?php
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
function push($array1,$array2){
$return = array();
foreach($array1 as $key => $value){
$return[] = $value;
}
foreach($array2 as $key => $value){
$return[] = $value;
}
return $return;
}
$array = push($array1,$array2);
$array = push($array,$array3);
print_r($array);
If you want to have an array of arrays, each element at a given index having the values of the three arrays at the respecting index, then:
$length = count($array1);
$result = array();
for ($index = 0; $index < $length; $index++) {
$result[]=array($array1[$index], $array2[$index], $array3[$index]);
}
If you simply want to put all items into a new array, then:
$result = array();
for ($index = 0; $index < count($array1); $index++) {
$result[]=$array1[$index];
}
for ($index = 0; $index < count($array2); $index++) {
$result[]=$array2[$index];
}
for ($index = 0; $index < count($array3); $index++) {
$result[]=$array3[$index];
}
Use Array Merge
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = array_merge($array1,$array2,$array3);
echo "<pre>";
print_r($output);
echo "</pre>";
Ive got 2 arrays, first one contains values of objects, and second one contains their IDs.
In this form:
$values[0] applies to $ids[0]
$values[1] applies to $ids[1]
I need to sort first array (using sort() ) from lowest to highest (values are ints) - That's not problem.
Problem is, that When I sort array with values, I will lost ID of that value.
My question is: How to make that
If $values[0] turns to $values[5], automatically turn $ids[0] to $ids[5]
Thanks
Update:
Content of $values and $ids:
$values[0] = 1.5;
$values[1] = 2.4;
$values[2] = 15.7;
$values[3] = 11.7;
$values[4] = 4.8;
$values[5] = 0.4;
$ids[0] = 1;
$ids[1] = 2;
$ids[2] = 3;
$ids[3] = 4;
$ids[4] = 5;
$ids[5] = 6;
Combine the arrays first, then sort by key:
$newArr = array_combine($ids, $values);
ksort($newArr);
It sounds like you're looking for array_combine():
Example
<?php
$ids = array(2, 1, 3); // IDs
$values = array(a, b, c); // Values
$array = array_combine($ids, $values); // Combine arrays as ID => Value
ksort($arrays); // Sort new array
print_r($array); // Echo array
Output
Array
(
1 => b,
2 => a,
3 => c,
)
Follow the code below... have not tested it ... but it must work.... Easy to understand..
<?php
$count = count($values);
for($i = 0; $i<$count; $i++)
{
if($i == 0)
{
$sort1 = $values[$i];
$sort2 = $ids[$i];
$temp = 0;
}
if($sort1 > $values[$i])
{
$sort1 = $values[$i];
$sort2 = $ids[$i];
$temp_val = $values[$temp];
$temp_id = $ids[$temp];
$values['temp'] = $values[$i];
$ids['temp'] = $ids[$i];
$temp = $i;
$values[$i] = $temp_val;
$ids[$i] = $temp_id;
}
}
?>
$test = 'test1/test2/test3/test4';
I am trying to get a array from that $test above which i'd like to output like below.
Array
(
[0] => /
[1] => /test1/
[2] => /test1/test2/
[3] => /test1/test2/test3/
[4] => /test1/test2/test3/test4/
)
I've tried loops but can't quite figure out how to get it quite right.
Try to make loop like :
$test = 'test1/test2/test3/test4';
$test_arr = explode("/", $test);
$test_size = count($test_arr);
$count = 1;
$new_test_arr = array('/');
for ($i=0; $i<$test_size; $i++)
{
$new_test_arr[$count] = $new_test_arr[$i] . $test_arr[$i] . "/"
$count++;
}
Here's a way to do it very compactly:
$parts = explode("/", $test);
for($i = 0; $i <= count($parts); ++$i) {
echo "/".implode("/", array_slice($parts, 0, $i))."\n";
}
Not terribly efficient, but I don't think efficiency would matter in something trivial you 'd only do once. On the plus side, the loop modifies no variables which makes it easier to reason about.
See it in action.
A very easy and simple way, for this case would be
$test = 'test1/test2/test3/test4';
$arr = explode("/", $test);
$t = "";
$newArray = array("/");
foreach($arr as $value) {
$t .= "/".$value;
$newArray[] = $t;
}
print_r($newArray);
Demo
I know it'd be trivial to code myself, but in the interest of not having more code to maintain if it's built in to PHP already, is there a built-in function for "compressing" a PHP array? In other words, let's say I create an array thus:
$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;
What I want is an array where $array[0] == 5, $array[1] == 7, $array[2] == 9.
I could do this:
function array_defragment($array) {
$squashed_array = array();
foreach ($array as $item) {
$squashed_array[] = $item;
}
return $squashed_array;
}
...but it seems like the kind of thing that would be built in to PHP - I just can't find it in the docs.
Just use array_values:
$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;
$array = array_values($array);
var_dump($array === array(5, 7, 9));
A newer method is the spread operator ...
$arr = ['red', 'orange', 'yellow', 'green'];
unset($arr[2]);
$arr = [...$arr];
print_r($arr);
Gives me a result:
Array
(
[0] => red
[1] => orange
[2] => green
)
However, do keep in mind, the spread operator ... is significantly slower as a proportion in comparison to array_values. You may run the following test:
<?php
function getTimeNow()
{
return microtime(true) * 1000;
}
$arr1 = [];
for ($i = 0; $i < 100000; $i++) {
$arr1[$i + rand(0,4)] = $i;
}
$start = getTimeNow();
$spreadTest = [...$arr1];
echo "\nTime taken for spread: " . getTimeNow() - $start;
$start = getTimeNow();
$arrayValues = array_values($arr1);
echo "\nTime taken for array_values: " . getTimeNow() - $start;
Results are:
$ php index.php
Time taken for spread: 0.8779296875
Time taken for array_values: 0.4228515625