Search array and return multiple matches [duplicate] - php

This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 8 years ago.
For example if I am searching for a key with a value 5 in my array $cake, I could use the following code:
$cake = array("a"=>6,"b"=>5,"c"=>6);
echo array_search(5, $cake, true); // returns "b";
But if my $cake array contains multiple matches, only the first match is returned:
$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
echo array_search(5, $cake, true); // returns "b";
How can I return multiple matches as an array? Like this:
$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
// return array("b","c","d","e");

As noted in the docs:
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
print_r(array_keys($cake, 5, true));

You can use array_intersect.
array_intersect — Computes the intersection of arrays
$matches = array_keys(array_intersect($cake, array(5)));
print_r($matches);
Outputs
Array
(
[0] => b
[1] => c
[2] => d
[3] => e
)

you can do this:
for($index = 0; $index <= count($cake); $index++){
if(!array_search(5, $cake[$index], true) == false){
echo array_search(5, $cake[$index], true);
}
}

Related

How to get the first unique number in array using PHP?

Consider an array [1,2,1,2,3,4,5,]. I need to make a function in PHP that will return the first unique number in that array, in this case, 3.
Or
How we can remove all repeated elements of the array. In this case returns [3,4,5].
You can use following snippet,
$yourArr = [1,2,1,2,3,4,5];
// count the number of occurences of each value
$res = array_count_values($yourArr);
// filtering only unique values
$res = array_filter($res, function($item){ return $item == 1; });
print_r();
// to fetched first unique
// fetching filtered values as keys
$un = array_keys($res);
echo $un[0]; // will output 3
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
Working Demo
Output:-
Array
(
[0] => 3
[1] => 4
[2] => 5
)

How to get array value that doesn't exist in another array [duplicate]

This question already has answers here:
Using array_diff(), how to get difference from array2 instead of array1?
(4 answers)
difference between two arrays
(7 answers)
Closed 5 years ago.
I have two arrays, each generated from a string. The strings are:
$string1 = "#574390, #574387, #574386, #574383 (keyboard enter)
#574368, #574367, #574364, #574361, #574357, #574355, #574351, #574343, #574341 (keyboard enter)
#574381, #574379, #574377, #574375, #574374, #574373, #574372, #574371, #574369"
$string2 = "574390
574386
574383
574381
574379
574377
574375
574374
574373
574372
574371
574369
574368
574367
574364
574361
574357
574355
574351
574343
574341"
Then, I do this to explode each string to array:
$str1 = checkstring($string1);
$str2 = checkstring($string2);
function checkstring($x) {
//check whether the string has "#" in it
if (!strstr($x, '#')) {
$array1 = str_replace(" ", "", $x);
$array1 = explode("\n", str_replace("\r", "", $array1));
return $array1;
}
else {
$array2 = str_replace("\r", ", ", str_replace("#", '', $x));
$array2 = array_unique(explode(", ", $array2), SORT_REGULAR);
return $array2;
}
}
After that, I try to find the difference between the two array:
$result = array_diff($str1, $str2);
print_r($result);
As you can see, the difference between array 1 and array 2 is that in array 1 there is 574387 but not in array 2. The result that I get from the code is this:
Array ( [1] => 574387 [4] => 574368 [13] => 574381 )
And if I switch the value between $string1 and $string2 the result will be this:
Array ( [3] => 574381 [12] => 574368 )
I do the switching because I want to make it able to check both ways. I was wondering what's wrong with it.
Thanks for the help.
[array_diff] Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
Taken from php.net
So, it only shows the elements of array1 (in your case $str1), which are different to the compared arrays (in your case $str2). That is why 574387 is not shown in the second comparison. Also, the other two differences are shown, because instead of using a comma, you use a (keyboard enter) in front of them in $str1.
If you want to see the differences from both arrays, try something like this:
array_merge(array_diff($str1,$str2),array_diff($str2,$str1));
You can try this
preg_match_all('/[0-9]+/', $string1, $result);
$array1 = array_unique($result[0]);
preg_match_all('/[0-9]+/', $string2, $result);
$array2 = array_unique($result[0]);
$arrayDiff = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
print_r($arrayDiff);

PHP: How to delete all array elements after an index [duplicate]

This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested

php check array value for duplicate [duplicate]

This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 9 years ago.
i have this below array:
PHP
$arr=array('A','A','B','C');
i want to check value and if values are duplicate must be alert error
PHP
$chk=array_count_values($array);
if ( $chk[0] < 1 || $chk[2] < 1 || $chk[3] < 1 || $chk[4] < 1 )
echo 'array must be uniq';
Using array_unique(), this can be easily refactored into a new function:
function array_is_unique($array) {
return array_unique($array) == $array;
}
Example:
$array = array("a", "a", "b", "c");
echo array_is_unique($array) ? "unique" : "non-unique"; //"non-unique"
Try this :
$arr = array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
echo "array must be uniq";
}
Just try with:
if ( count($arr) != count(array_unique($arr)) ) {
echo 'array must be uniq';
}
You could walk thhrough it with a foreach loop and then use the strpos function to see if a string contains duplicates
From Php documentation
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.

Want to got the new array that not in array A?

I have two arrays:
$A = array('a','b','c','d')
$c = array('b','c','e','f')
I want to get a new array containing items not in array $A. So it would be:
$result = array('e','f');
because 'e' and 'f' are not in $A.
Use array_diff
print_r(array_diff($c, $A)); returns
Array
(
[2] => e
[3] => f
)
Use array_diff for this task. As somewhat annoying it does not return all the differences between the two arrays. Only the elements from the first array passed which are not found in any other array passed as argument.
$array1 = array('a','b','c','d');
$array2 = array('b','c','e','f');
$result = array_diff($array2, $array1);
array_diff()
Pseduo Code for General Implementation
Disclaimer: Not familiar with PHP, other answers indicate there are a lot quicker ways of doing this :)
Loop through your first array:
// Array of results
array results[];
// Loop through all chars in first array
for i = 0; i < A.size; i++
{
// Have we found it in second array yet?
bool matched = false;
// Loop each character in 2nd array
for j = 0; j < C.size; j++
{
// If they match, exit the loop
if A[i] == C[J] then
matched = true;
exit for;
}
// If we have a match add it to results
if matches == true then results.add(A[i])
}

Categories