If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.
Input arrays
arr1={1,4,6,7,8};
arr2={1,7,7,6,8};
Result array
arr2={true,false,false,false,true};
Is there a function in php to get result as above or should it be done using loop(which I can do) only.
This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)
$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);
$r = array_map(function($a1, $a2) {
return $a1 === $a2;
}, $a1, $a2);
var_dump($r);
/*
array(5) {
[0]=>
bool(true)
[1]=>
bool(false)
[2]=>
bool(false)
[3]=>
bool(false)
[4]=>
bool(true)
}
*/
And yes, you have to loop over the array some way or the other.
You could use array_map:
<?php
$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;
function cmp ($a, $b) {
return $a == $b ;
}
print_r (array_map ("cmp", $arr1, $arr2)) ;
?>
The output is:
Array
(
[0] => 1
[1] =>
[2] =>
[3] =>
[4] => 1
)
Any way this job is done must be using looping the elements. There is no way to avoid looping.
No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.
You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.
there's array_diff() which will return an empty array in case they are both equal.
For your spesific request, you'll have to iterate through the arrays and compare each item.
Related
I am working with PHP,I have array and i want to change position of array, i want to display matching value in first position,For example i have following array
$cars=('Toyota','Volvo','BMW');
And i have variable $car="BMW" And i want to match this variable with array and if match then this array value should be at first in array
so expected result is (matching record at first position)
$cars=('BMW','Volvo','Toyota');
How can i do this ?
You can use array_search and array_replace for this purpose. try below mentioned code
$cars=array(0 =>'Toyota',1 =>'Volvo',2 =>'BMW');
$car="BMW";
$resultIndex = array_search($car, $cars); //get index
if($resultIndex)
{
$replacement = array(0 =>$car,array_search($car, $cars)=>$cars[0]); //swap with 0 index
$cars = array_replace($cars, $replacement); //replace
}
print_r($cars);
This can be solved in one line with array_merge and array_unique array functions.
$cars=['Toyota','Volvo','BMW'];
$car="BMW";
$cars2 = array_unique(array_merge([$car],$cars));
//$cars2: array(3) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" [2]=> string(5) "Volvo" }
$car is always at the beginning of the new array due to array_merge. If $car already exists in the $cars array, array_unique will remove it. If $car is not present in the $cars array, it is added at the beginning. If this behavior is not desired, you can use in_array to test whether $car is also contained in the $cars array.
The simplest is to "sort" by "Value = BMW", "Value != BMW".
The function that sorts and resets the keys (i.e. starts the resulting array from 0, which you want) is usort (https://www.php.net/manual/en/function.usort.php)
So your comparison function will be If ($a == "BMW") return 1, elseif ($b == "BMW") return -1, else return 0; (Paraphrased, don't expect that to work exactly - need to leave a bit for you to do!)
I got an empty array when I compare two arrays that have the different key but the same value. Example: id has the same value like yy
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
What I want is :
$a = array('id'=>12,'id'=>2);
You can use array_merge_recursive() - (PHP 4 >= 4.0.1, PHP 5, PHP 7)
From PHP Manual:
array_merge_recursive — Merge two or more arrays recursively
<?php
$a = array('id'=>2,'name'=>'D','yy'=>12);
$b = array('id'=>12,'name'=>'D','yy'=>12);
$result = array_merge_recursive($a, $b);
$newArr = $result['id']; // get ID index. you can also get other indexes.
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => 2
[1] => 12
)
Note that: you can not use same index name (ID) for this array array('id'=>12,'id'=>2);
As #Ghost mentioned, an associative array should not have the same keys.
I suggest to achieve the "expected result" in "nested arrays" manner using array_diff_assoc function(computes the difference of arrays with additional index check):
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
echo "<pre>";
$result_nested_arr = [array_diff_assoc($o, $n), array_diff_assoc($n, $o)];
var_dump($result_nested_arr);
// the output:
array(2) {
[0]=>
array(1) {
["id"]=>
int(2)
}
[1]=>
array(1) {
["id"]=>
int(12)
}
}
http://php.net/manual/en/function.array-diff-assoc.php
I'm trying to remove specific element from php array with unset function. Problem is that when I var_dump array it shows all indexes (not good) but If I try to var_dump specific index PHP throws warning (good).
$a = [
'unset_me',
'leave_me',
'whatever',
];
unset($a['unset_me']);
var_dump($a);
/**
array(3) {
[0]=>
string(8) "unset_me"
[1]=>
string(8) "leave_me"
[2]=>
string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me
Question is why php behave like this and how to remove index properly?
One more solution:
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
// remove the elements that you want
$arr = array_diff($arr, array("unset_me"));
print_r($arr);
You can try this with array_search -
unset($a[array_search('unset_me', $a)]);
If needed then add the checks like -
if(array_search('unset_me', $a) !== false) {
unset($a[array_search('unset_me', $a)]);
}
Demo
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
echo '<br/>';
$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);
print_r($arr);
I recently encountered this problem and found this solution helped:
unset($a[array_flip($a)['unset_me']]);
Just to explain what is going on here:
array_flip($a) switches the items for the key. So it would become:
$a = [
'unset_me' => 0,
'leave_me' => 1,
'whatever' => 2,
];
array_flip($a)['unset_me'] therefore resolves to being 0. So that expression is put into the original $a which can then be unset.
2 caveats here:
This would only work for your basic array, if you had an array of objects or arrays, then you would need to choose one of the other solutions
The key that you remove will be missing from the array, so in this case, there will not be an item at 0 and the array would start from 1. If it is important to you, you can do array_values($a) to reset the keys.
I need to print contents of multiple arrays in my code. Eg
function performOp($n, $inputArr, $workArr)
{
printf("Entered function, value of n is %d", $n);
print_r($inputArr);
print_r($workArr);
$width =0;
}
Now, Instead of writing print_r twice, is there any way I can write a single statement and print both the arrays ?
Also, If I want to print "Input array value is " before displaying the Array{}, is there a way to do so using printf or any other function?
I tried writing printf("Value of inputArray is %s ", print_r($inputArr), but this would not work.
Any help is really appreciated.
Thanks
Dumping the Variables
You can pass multiple arrays into var_dump().
var_dump( $array, $array2, $array3 );
For instance, the following:
$array = array("Foo", "bar");
$array2 = array("Fizz", "Buzz");
var_dump( $array, $array2 );
Outputs this:
array(2) { [0]=> string(3) "Foo" [1]=> string(3) "bar" }
array(2) { [0]=> string(4) "Fizz" [1]=> string(4) "Buzz" }
Note how it keeps both arrays distinct in the output as well.
Function with n-arguments
You could also use a function, calling upon func_get_args() for the arrays passed in:
function logArrays() {
$arrays = func_get_args();
for ( $i = 0; $i < func_num_args(); $i++ )
printf( "Array #%d is %s", $i, print_r($arrays[$i], true) );
}
logArrays( $array, $array2 );
Which, in this case, would output the following:
Array #0 is Array ( [0] => Foo [1] => bar )
Array #1 is Array ( [0] => Fizz [1] => Buzz )
Using json_encode() instead of print_r would output a slightly more readable format:
Array #0 is ["Foo","bar"]
Array #1 is ["Fizz","Buzz"]
User array_merge() to combine the arrays and then you can print them together.
If you prefer to use less function and have the advantage and simplicity of print_r() you combine these input value into new array inside the print_r(),
e.g I use this function to print raw unformatted output if my code (for debug) and this is the easiest method I reach.
function pre( $txt ) {
print_r( [ '<xmp> ' , $txt ,' </xmp> ' ] );
}
array(2) {
[0]=>
object(stdClass)#144 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(5) "name1"
}
[1]=>
object(stdClass)#145 (2) {
["id"]=>
string(1) "4"
["name"]=>
string(5) "name2"
}
}
I want to add key and value (for example [distance] = 100;) to the objects in the array. After this I want to sort on the distance values. How can I achieve this?
To get structure such as yours you can do:
$arr = array();
$arr[0]->id = "2";
$arr[0]->name = "name1";
$arr[1]->id = "4";
$arr[1]->name = "name2";
To add "distance" you can do:
$arr[0]->distance = 100;
$arr[1]->distance = 200;
To sort you can use decorate/sort/undecorate pattern:
$arr = array_map(create_function('$o', 'return array($o->distance, $o);'), $arr); // transform array of objects into array of arrays consisted of sort key and object
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array
Or you can use usort() with custom comparison function like this:
function compareDistanceFields($a, $b) {
return $a->distance - $b->distance;
}
usort($arr, "compareDistanceFields");
$my_array[0]->distance = 100;
$my_array[0]->distance = 101;
usort($my_array, "cmp");
function cmp($a, $b)
{
if ($a->distance == $b->distance)
return 0;
return ($a->distance > $b->distance) ? 1: -1;
}
What you have here is an array of hashes; that is, each element of your array is a hash (a structure containing elements, each of which is identified by a key).
In order to add a key and value, you just assign it, like this:
$array[0]["distance"]=100;
$array[1]["distance"]=300;
#and so on
PHP hashes and arrays in general are documented here.
Now, in order to sort your array (each of whose elements is a hash), you need to use the "uasort" function, which allows you to define a comparison function; in this comparison function you define the behavior you want, which is sorting on the value of the distance key.
Something like this:
// Comparison function, this compares the value of the "distance" key
// for each of the two elements being compared.
function cmp($a, $b) {
if ($a["distance"] == $b["distance"]) {
return 0;
}
return ($a["distance"] < $b["distance"]) ? -1 : 1;
}
Once this is defined, you call uasort like this:
uasort($array, 'cmp');
Find more documentation on uasort here.