php - find array value that has pattern index - php

I have an array like :
$a =['main'=>
[
'a' => ['1st'],
'b' => ['2nd'],
'c' => ['3th']
];
and I want do like:
if(in_array('1st', $a['main'][x])){
...
}
I need x(now it is a) value too

$resulting_keys = [];
foreach($a['main'] as $key => $value) {
if(in_array('1st', $value)) {
$resulting_keys[] = $key;
}
}

here are working example:
$a = array(
'main'=> array(
'a' => '1st',
'b' => '2nd',
'c' => '3th'
)
);
if(in_array('1st', $a['main'])){
echo 'Yes';
}else{
echo 'No';
}

Maybe try this:
array_filter($a['main'], function($el) {
return in_array('1st', $el);
})
Array filter function is a good solution to filter arrays
http://php.net/manual/en/function.array-filter.php

Related

Obtain key from array through value

How can I obtain a key in a array just by knowing it's value? For example, here is an array:
$array = Array("Item1" => array("Number" => "One", "Letter" => "A"));
Just by knowing "One" or "A", how can I get the main key name, Item1?
I've looked into array_key_value and in_array but I do not think that those functions are helpful for my kind of array.
Since it is a 2d array, you will want to search the inner array for the value so you would have to make your own function to do this. Something like this:
function findInArray($array, $lookup){
//loop over the outer array getting each key and value.
foreach($array as $key=>$value){
//if we found our lookup value in the inner array
if(in_array($lookup, $value)){
//return the original key
return $key;
}
}
//else, return null because not found
return null;
}
$array = Array("Item1" => array("Number" => "One", "Letter" => "A"));
var_dump(findInArray($array, 'One')); //outputs string(5) "Item1"
var_dump(findInArray($array, 'Two')); //outputs null
Demo: https://3v4l.org/oRjHK
This function may help you
function key_of_value($array, $value){
foreach($array as $key=>$val){
if(in_array($value, $val)){
return $key;
}
}
return null;
}
echo key_of_value(['Item1'=>['One','Two','Three','Hello',2,6]],'A');
There is no way around iterating through your data. This might be a little more elegant than two foreach loops:
<?php
$match = null;
$needle = 'Two';
$haystack = [
'Item1' => [
'Number' => 'One',
'Letter' => 'A'
],
'Item2' => [
'Number' => 'Two',
'Letter' => 'B'
],
'Item3' => [
'Number' => 'Three',
'Letter' => 'C'
],
];
array_walk($haystack, function($entry, $key) use ($needle, &$match) {
if(in_array($needle, $entry)) {
$match = $key;
}
});
var_dump($match);
The output obviously is:
string(5) "Item2"
You can use array_walk_recursive to iterate on array values recursive. I write a function that return main key of searched value in nested arrays.
<?php
$array = array("Item1" => array("Number" => "One", "Letter" => "A", 'other' => array('Number' => "Two")));
echo find_main_key($array, 'One'); //Output: "Item1"
echo find_main_key($array, 'A'); //Output: "Item1"
echo find_main_key($array, 'Two'); //Output: "Item1"
var_dump(find_main_key($array, 'nothing')); // NULL
function find_main_key($array, $value) {
$finded_key = NULL;
foreach($array as $this_main_key => $array_item) {
if(!$finded_key) {
array_walk_recursive($array_item, function($inner_item, $inner_key) use ($value, $this_main_key, &$finded_key){
if($inner_item === $value) {
$finded_key = $this_main_key;
return;
}
});
}
}
return $finded_key;
}
This is how I would do it:
foreach($array as $key => $value) {
if(in_array('One', $value)) echo $key;
}

PHP: Find last occurence of string in array

I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
I want $key = 3 which is the last matched element.
Any suggestion appreciated.
PHP code demo
<?php
ini_set("display_errors", 1);
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
$index=$key;
unset($Data[$key]);
}
echo $index;
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.
$data = array_flip($Data);
echo $data['bike'];
after the flip, only keep the last element of the same elements. Here is the print_r($data)
Array
(
[car] => 0
[bike] => 3
[bus] => 2
[boat] => 4
)
We can use array_reverse to reverse array.
$key = array_search('bike', array_reverse($Data,true));
It will return 3.
you can use krsort to sort the array by key.
krsort($Data);
$key = array_search('bike', $Data);
echo $key;
Working example: https://3v4l.org/fYOgN
For this I am created one function it is very easy to use. You can pass only array and parameters.
function text_to_id($value, $arr_master) {
$id_selected = 0;
$search_array = $arr_master;
if (in_array($value, $search_array)) {
$id_selected = array_search($value, $search_array);
// pr($id_selected);exit;
}
if (!$id_selected) {
foreach ($search_array as $f_key => $f_value) {
if (is_array($f_value)) {
if (in_array($value, $f_value)) {
$id_selected = $f_key;
break;
}
} else if ($value == $f_value) {
$id_selected = $f_key;
break;
}
else;
}
}
return $id_selected;
}
this function use like this
$variable = text_to_id('bike', $your_array);

PHP Find a value in a key and get the value of another key in a multi-dimentional array

Might be a newbie question but I've been trying to figure this problem and it's doing my head in.
I have the following array :
[0] => Array
(
[provisionalBookingRoomID] => 1
[totalSpecificRoomCount] => 2
)
[1] => Array
(
[provisionalBookingRoomID] => 2
[totalSpecificRoomCount] => 5
)
I need a php function that searches through the array for the value of 'provisionalBookingRoomID' and returns the value of 'totalSpecificRoomCount'
basically something like the following
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms);
// getProvisionalTotalRoomsCount('1', $arrayOfRooms) should return 2;
Any ideas?
Check this:
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms){
foreach($arrayOfRooms as $key=>$value){
if($value['provisionalBookingRoomID'] == $currentRoom){
return $value['totalSpecificRoomCount'];
}
}
}
For anyone looking for a generic function :
function findValueInArray($array, $searchValue, $searchKey, $requiredKeyValue) {
foreach($array as $key=>$value){
if($value[$searchKey] == $searchValue){
return $value[$requiredKeyValue];
}
}
}
// Usage : findValueInArray($provisionalBookedRoomsArray, '1', 'provisionalBookingRoomID', 'totalSpecificRoomCount');
If you are likely to work with more than one value, you could build a new array with a 1->1 map for those attributes.
<?php
$items = array(
array(
'name' => 'Foo',
'age' => 23
),
array(
'name' => 'Bar',
'age' => 47
)
);
// Php 7
$name_ages = array_column($items, 'name', 'age');
echo $name_ages['Foo']; // Output 23
// Earlier versions:
$name_ages = array();
foreach($items as $value)
{
$name_ages[$value['name']] = $value['age'];
}
echo $name_ages['Foo']; // Output 23
$value = 0;
$array = array(array("provisionalBookingRoomID"=>1,"totalSpecificRoomCount"=>2),array("provisionalBookingRoomID"=>2,"totalSpecificRoomCount"=>5));
array_map(
function($arr) use (&$value) {
if($arr['provisionalBookingRoomID']==1) {
$value = $arr['totalSpecificRoomCount'];
}
},$array
);
echo $value;

Remove empty and null value recursively from PHP array

I have an array like this
$a = array(
'b' => array(
'two' => false,
'three' => '',
'four' => null,
'five' => array(
'fp' => null,
'kp' => null
),
'six' => array()
),
'c' => ' ',
'd' => null
);
I want to remove only null and empty keys from this n-level array. And finally I should get this:
$a = array(
'b' => array(
'two' => false
),
'c' => ' '
);
I have this function
public function ArrayCleaner($input) {
foreach ($input as &$value) {
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input);
}
But, as array_filter states, it will also remove false value key (that I want to preserve). So what change I should make in my function to achieve the expected result?
You are close, just change your code like below by providing the callback function for filtering:
function ArrayCleaner($input) {
foreach ($input as &$value) {
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input, function($item){
return $item !== null && $item !== '';
});
}
function ArrayCleaner($input) {
foreach ($input as $key=>&$value) {
if(is_int($key)){
unset($input[$key]);
continue;
}
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input, function($item){
return $item !== null && $item !== '';
});
}
But Question: what does empty key mean? 'one' indicates its index is number 0. So if we filter it by using something like is_int($key) , how to deal with '2'=>'this data?' ? it will convert to int(2) in php Array.

How do I check if array value is empty?

Here is my array ouput
Array
(
[1] => 1
[2] => 2
[3] =>
)
How do I know the [3] => is empty?
foreach ($array as $key => $value) {
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
My out put showing all is not empty. What is correct way to check is empty?
An other solution:
$array = array('one', 'two', '');
if(count(array_filter($array)) == count($array)) {
echo 'OK';
} else {
echo 'ERROR';
}
http://codepad.org/zF9KkqKl
It works as expected, third one is empty
http://codepad.org/yBIVBHj0
Maybe try to trim its value, just in case that third value would be just a space.
foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
You can check for an empty array by using the following:
if ( !empty(array_filter($array))) {
echo 'OK';
} else {
echo 'EMPTY ARRAY';
}
You can use array_diff() and array_diff_key():
$array = array('one', 'two', '');
$emptyKeys = array_diff_key(array_diff($array,array()),$array);
array_diff() extracts all items which are not the same (therefore leaving out the blanks), array_diff_key gives back the differences to the original array.
$array = array('A', 'B', '');
or
$array = array('A', 'B', ' ');
An other solution:
this work for me
if(in_array(null, $myArray) || in_array('', array_map('trim',$myArray))) {
echo 'Found a empty value in your array!';
}
Here is a simple solution to check an array for empty key values and return the key.
$a = array('string', '', 5);
echo array_search(null, $a);
// Echos 1
To check if array contains an empty key value. Try this.
$b = array('string','string','string','string','','string');
if (in_array(null, $b)) {
echo 'We found a empty key value in your array!';
}
im using in my project like this for check this array
im posting form data like this array('username' => 'john','surname' => 'sins');
public function checkArrayKeyExist($arr) {
foreach ($arr as $key => $value) {
if (!strlen($arr[$key])) {
return false;
}
}
return true;
}
Try this:
<?php
$data=array(
'title' => 'Test Name Four',
'first_name' => '',
'last_name' => 'M',
'field_company' => 'ABC',
'email' => '',
'client_phone_number' => '',
'address_line_1' => '',
'address_line_2' => 'Address 3',
'address_line_3' => '',
'address_line_4' => '',
'post_code' => '',
);
echo '<pre>';
print_r($data);
foreach ($data as $key => $case ) {
echo "$key => ".is_multiArrayEmpty($case)."<br>";
}
function is_multiArrayEmpty($multiarray) {
if(is_array($multiarray) and !empty($multiarray)){
$tmp = array_shift($multiarray);
if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
return false;
}
return true;
}
if(empty($multiarray)){
return true;
}
return false;
}
?>

Categories