Search for value in array of associative arrays using php [duplicate] - php

This question already has answers here:
Search in array, like select?
(3 answers)
Closed 4 years ago.
How to find the array which contains moo == 'gyu'?
$arr = [
['moo' => 'abc', 'foo' => 1], ['moo' => 'gyu', 'foo' => 2] ...
]
I know that should be answered already but unfortunately I wasn't able to find an example.
Thank you.

Use array_filter() to to find target array. In callback function check value of moo index.
$newArr = array_filter($arr, function($item){
return $item['moo'] == 'gyu';
});
Also you can use array_reduce() that return target array in result.
$newArr = array_reduce($arr, function($carry, $item){
$item['moo'] == 'gyu' ? $carry = $item : "";
return $carry;
});
Check result in demo

You have to used array_search() function for that.
if(array_search('gyu', array_column($arr, 'moo')) !== False) {
echo "FOUND";
} else {
echo "Not Found";
}

Related

Multiple values in array excluding specified key [duplicate]

This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 9 months ago.
I'm trying to verify if certain values exist within an array excluding a specific key:
$haystack = array(
"id" => 1,
"char1" => 2,
"char2" => 3,
"char3" => 4,
);
$needles = array(2, 4);
Solution that I found here: in_array multiple values
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
The problem is that I'm checking if certain chars exist within the array. This will work fine in this case:
$exists = in_array_all([2, 4], $haystack); // true
But it'll cause an issue in this situation:
$exists = in_array_all([1, 3], $haystack); // true
It found the value 1 in the key id and therefor evaluates as true while a char with id 1 is not within the array. How can I make it so that it excludes the key id within the search?
Note: This is example data. The real data is much larger, so just using if / else statements isn't really viable.
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
function excludeKeys($haystack){
$tempArray = array();
foreach($haystack as $key => $value){
if ($key == "id"){
// Don't include
}else{
$tempArray[$key] = $value;
}
}
return $tempArray;
}
$haystack = array(
"id" => 1,
"char1" => 2,
"char2" => 3,
"char3" => 4,
);
$exists = in_array_all([1, 3], excludeKeys($haystack));
echo("Exists: ".($exists ? "Yes" : "No"));
This basically just returns the array without the keys you specify. This keeps the original array in tact for later use.
Edit:
These bad solutions are really a symptom of a problem in your data structure. You should consider converting your array to an object. It looks like this:
$object = new stdClass();
$object->id = 1;
$object->chars = array(2, 3, 4);
$exists = in_array_all([1, 3], $object->chars);
This is how you're supposed to separate your data up. This way you can properly store your information by key. Furthermore you can store other objects or arrays within the object specific to a key, as shown above.
Unset id index and then do search:
function in_array_any($needles, $haystack) {
unset($haystack['id']);
return !array_diff($needles, $haystack);
}
https://3v4l.org/PTjOS

Dividing array by comparing flag using array functions in php [duplicate]

This question already has answers here:
Split associative array by key
(6 answers)
Get the first N elements of an array?
(5 answers)
php - get numeric index of associative array
(7 answers)
Closed 2 years ago.
There is an array in php
$sampleArray = array('first' => 'first', 'second' => 'second', 'third' => 'third');
I need to splitting the array based on value $check, if the $check is 'second', then the array need to be split like this
$requiredArray = array('third'=>'third')
$nonReqArray = array('first'=>'first','second'=>'second')
if the $check is 'third' then the $requiredArray will be empty. Please suggest the solution to this?
Tried with this
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check) {
if($key > $check){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
return true;
},
ARRAY_FILTER_USE_KEY);
Usually solved with for loops. But we can solve by array_filter array function. The main issue is indexing is not numerical, so comparing is not easy.
$cmp = false;
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check, &$cmp) {
if($cmp){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
if($key == $check){
$cmp =true;
}
return true;
},
ARRAY_FILTER_USE_KEY);
This worked for me.

Array_Search For Multiple Same Elements [duplicate]

This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 2 years ago.
there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?
i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'
how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?
your help will be highly appreciated
You can use array_keys with search value PHP Doc
Demo
array_keys($arr,3)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the array are returned.
you can use array_keys:
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
ARRAY_FILTER_USE_BOTH
);
$threes Is an array containing all keys having the value 3.
array(3) { 2, 4, 5 }

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

How can you sort each element inside of an array alphabetically [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 8 years ago.
For example we have the following words: hey, hello, wrong
$unsorted = array("eyh", "lhleo", "nrwgo");
I know that I could use asort to sort the array alphabetically, but I don't want that.
I wish to take the elements of the array and sort those, so that it would become something like this:
$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted
hey sorted = ehy
hello sorted = ehllo
wrong sorted = gnorw
As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.
Thanks in advance!
function sort_each($arr) {
foreach ($arr as &$string) {
$stringParts = str_split($string);
sort($stringParts);
$string = implode('', $stringParts);
}
return $arr;
}
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
$myArray,
function (&$value) {
$value = str_split($value);
sort($value);
$value = implode($value);
}
);
print_r($myArray);
Try this
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString = implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);

Categories