Search number in array - php

$record_record contains:
Array
(
[0] => Array
(
[id] => 252
[origin] => laptop.me.
)
[1] => Array
(
[id] => 255
[origin] => hello.me.
)
[2] => Array
(
[id] => 254
[origin] => intel.me.
)
)
I need to search if 255 is exist in the array. The code below didn't work.
if (in_array('255', $record_record, true)) {
echo "'255' found with strict check\n";
}
else {
echo "nope\n";
}
I had a feeling because it's a nested array the function will not work. Help me please?

You need to do something like this:
<?php
function id_exists ($array, $id, $strict = FALSE) {
// Loop outer array
foreach ($array as $inner) {
// Make sure id is set, and compare it to the search value
if (isset($inner['id']) && (($strict) ? $inner['id'] === $id : $inner['id'] == $id)) {
// We found it
return TRUE;
}
}
// We didn't find it
return FALSE;
}
if (id_exists($record_record, 255, true)) {
echo "'255' found with strict check\n";
} else {
echo "nope\n";
}

Do something like :
foreach($record_record as $sub_array){
if (in_array('255', $sub_array, true)) {
echo "'255' found with strict check\n";
}
else {
echo "nope\n";
}
}

You'll need a recursive function for that. From elusive:
function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Or, if your array structure will never change, just write a simple loop:
function in_2dimensional_array($needle, $haystack, $strict = true){
foreach ($haystack as $item) {
if (in_array($needle, $haystack, true)) {
return true;
}
}
return false;
}

Hacky solution. Someone else will post a nice one using array_map or something similar.
function in_nested_array($val, $arr)
{
$matched = false;
foreach ($arr AS $ar)
{
if (in_array($val, $ar, true)
{
$matched = true;
break;
}
}
return $matched;
}
if (in_nested_array(255, $record_record))
{
// partay
}

<?php
foreach($record_record as $record) {
$key = array_search('255', $record);
if ($key) {
echo "'255' found with strict check\n";
}
}
?>

Related

Search inside multidimensional array and return other key value

I have the following
Multidimensional array.
What I'm trying to do is to search for an IDITEM value and if it's found, return the value of the "PRECO" key.
I'm using the following function to check if the value exists and it works fine, but I can't find a way to get the "PRECO" value of the found IDITEM.
Function:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
Anyone can help me with that?
You can change the first if statement to return it instead of returning a boolean :
function search_array($needle, $haystack) {
if(in_array($needle, $haystack) && array_key_exists('PRECO', $haystack)) {
return $haystack['PRECO'];
}
foreach($haystack as $element) {
if(is_array($element))
{
$result = search_array($needle, $element);
if($result !== false)
return $result;
}
}
return false;
}
The easiest idea I can remember is converting that boolean search_array into a path creator, where it will return the path for the item, or false if it isn't found.
function get_array_path_to_needle($needle, array $haystack)
{
if(in_array($needle, $haystack))
{
return true;
}
foreach($haystack as $key => $element)
{
if(is_array($element) && ($path = get_array_path_to_needle($needle, $element)) !== false)
{
return $path === true ? $key : $key . '.' . $path;
}
}
return false;
}
Then, since you already have the path, then rerun the array to fetch the item
function get_array_value_from_path(array $path, array $haystack)
{
$current = $haystack;
foreach($path as $key)
{
if(is_array($current) && array_key_exists($key, $current))
{
$current = $current[$key];
}
else
{
return false;
}
}
return $current;
}
This wont get you the PRECO, but it will return the item (array) where id found the value you searched for.
So a simple usage would be:
$path = get_array_path_to_needle('000000000000001650', $data);
$item = get_array_value_from_path(explode('.', $path), $data);
// here you have full array for that item found
print_r($item);
// here you have your price
print_r($item['PRECO']);
Use a static variable to remember the status between multiple function calls, and also to store the desired PRECO value. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.
So your search_array() function should be like this:
function search_array($needle, $haystack){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key => $value){
if(is_array($value)){
search_array($needle, $value);
}else if($needle == $value){
$needle_value = $haystack['PRECO'];
break;
}
}
return $needle_value;
}
This function will finally return $needle_value, which is your desired PRECO value from the haystack.
The simplest way is to use a foreach loop twice. Check for the key and store the result into an array for later use.
Based on your array, the below
$search = '000000000000001650';
foreach($array as $element){
foreach ($element['ITEM'] as $item){
if (isset($item['IDITEM']) and $item['IDITEM'] == $search){
$results[] = $item['PRECO'];
}
}
}
print_r($results);
Will output
Array
(
[0] => 375
)
Here is the simple example with array:
// your array with two indexes
$yourArr = array(
0=>array(
'IDDEPARTAMENTO'=>'0000000001',
'DESCRDEPT'=>'Área',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001367',
'DESCRITEM'=>'PISTA TESTE DRIV',
'PRECO'=>'1338.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001925',
'DESCRITEM'=>'PISTA TESTE DRIV2',
'PRECO'=>'916'),
)
),
1=>array(
'IDDEPARTAMENTO'=>'0000000010',
'DESCRDEPT'=>'Merch',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000002036',
'DESCRITEM'=>'PISTA TESTE DRIV23',
'PRECO'=>'200.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001608',
'DESCRITEM'=>'PISTA CRACHÁ DRIV4',
'PRECO'=>'44341'),
)
));
// solution
$newArr = array();
foreach ($yourArr as $value) {
foreach ($value as $key => $innerVal) {
if($key == 'ITEM'){
foreach ($innerVal as $key_inner => $keyinner) {
if(!empty($keyinner['IDITEM'])){
$newArr[$keyinner['IDITEM']] = $keyinner['PRECO'];
}
}
}
}
}
echo "<pre>";
print_r($newArr);
Result values with IDITEM:
Array
(
[000000000000001367] => 1338.78
[000000000000001925] => 916
[000000000000002036] => 200.78
[000000000000001608] => 44341
)

check if string exists in array element

Is there any function that can do what strpos does, but on the elements of an array ? for example I have this array :
Array
(
[0] => a66,b30
[1] => b30
)
each element of the array can contain a set of strings, separated by commas.
Let's say i'm looking for b30.
I want that function to browse the array and return 0 and 1. can you help please ? the function has to do the oppsite of what this function does.
Try this (not tested) :
function arraySearch($array, $search) {
if(!is_array($array)) {
return 0;
}
if(is_array($search) || is_object($search)) {
return 0;
}
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) {
continue;
}
if(strpos($v, $search) !== false) {
return 1;
}
}
return 0;
}
You could also use preg_grep for this.
<?php
$a = array(
'j98',
'a66,b30',
'b30',
'something',
'a40'
);
print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );
https://eval.in/412598

Check if array value exists in multidimensional array

I read this question and it answered part of my question, but no matter what I do to modify the function, I'm not getting the expected results.
I want to pass an array to this function and check if a value of this array, exists in the multidimensional array. How can I modify this function to work if $needle is an array?
//example data
$needle = array(
[0] => someemail#example.com,
[1] => anotheremail#example.com,
[2] => foo#bar.com
)
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
EDIT
After reading the answer supplied by TiMESPLiNTER I updated my function as follows and it works perfectly.
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (is_array($needle) && is_array($item)) {
if(array_intersect($needle,$item)) {
return true;
}
}
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Check if array_intersect() returns an array with at least one element. If yes one of your values in the $needle array is contained in the $haystack array.
I ended up with this function:
function in_array_r($needle, $haystack) {
$flatArray = array();
array_walk_recursive($haystack, function($val, $key) use (&$flatArray) {
$flatArray[] = $val;
});
return (count(array_intersect($needle, $flatArray)) > 0);
}
You may extend this function to accept multidimensional arrays for both $needle and $haystack.

PHP - How i can find a partial word in array?

I have a word:
$word = "samsung";
I have array:
$myarray = Array(
[0] => "Samsung=tv"
[1] => "Apple=mobile"
[2] => "Nokia=mobile"
[3] => "LG=tv"
I need now something like this to find a partial match:
if($word in $myarray){ echo "YES"; } // samsung found in Samsung=tv
Thank you for help.
You want in_array http://us3.php.net/manual/en/function.in-array.php.
if(in_array($word,$myarray){ echo 'yes'; }
Are you looking for something like this?
<?php
$myarray = array("Samsung=tv", "Apple=mobile", "Nokia=mobile", "LG=tv");
function findSimilarWordInArray($word, $array) {
if (empty($array) && !is_array($array) return false;
foreach ($array as $key=>$value) {
if (strpos( strtolower($value), strtolower($word)) !== false) {
return true;
} // if
} // foreach
}
// use case
if ( findSimilarWordInArray('samsung',$myarray) ) {
echo "I've found it!";
}
?>
It allows you to look for a similar word in array values.
If you are looking for partial matches, you can use strpos() with a foreach loop to iterate through the array.
foreach ($myarray as $key => $value) {
if (strpos($value, $word) !== FALSE) {
echo "Yes";
}
}
There is no built in function to do a partial match, but you can easily create your own:
function in_array_partial($needle, $haystack){
$result = false;
$needle = strtolower($needle);
foreach($haystack as $elem){
if(strpos(strtolower($elem), $needle) !== false){
$result = true;
break;
}
}
return $result;
}
Usage:
if(in_array_partial('samsung', $myarray)){
echo 'yes';
}
You can try something like this:
function my_in_array($word, $array){
forach($array as $value){
if(strpos($word, $value) !== false){
return true;
}
}
return false;
}

best way to check a empty array?

How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
(
[title] =>
[description] =>
[price] =>
)
)
[product_data] => Array
(
[1] => Array
(
[title] =>
[description] =>
[price] =>
)
)
)
The array is not empty but there is no content. How can I check this with a simple function?
Thank!!
function is_array_empty($InputVariable)
{
$Result = true;
if (is_array($InputVariable) && count($InputVariable) > 0)
{
foreach ($InputVariable as $Value)
{
$Result = $Result && is_array_empty($Value);
}
}
else
{
$Result = empty($InputVariable);
}
return $Result;
}
If your array is only one level deep you can also do:
if (strlen(implode('', $array)) == 0)
Works in most cases :)
Solution with array_walk_recursive:
function empty_recursive($value)
{
if (is_array($value)) {
$empty = TRUE;
array_walk_recursive($value, function($item) use (&$empty) {
$empty = $empty && empty($item);
});
} else {
$empty = empty($value);
}
return $empty;
}
Assuming the array will always contain the same type of data:
function TestNotEmpty($arr) {
foreach($arr as $item)
if(isset($item->title) || isset($item->descrtiption || isset($item->price))
return true;
return false;
}
Short circuiting included.
function hasValues($input, $deepCheck = true) {
foreach($input as $value) {
if(is_array($value) && $deepCheck) {
if($this->hasValues($value, $deepCheck))
return true;
}
elseif(!empty($value) && !is_array($value))
return true;
}
return false;
}
Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.
function isEmpty($stringOrArray) {
if(is_array($stringOrArray)) {
foreach($stringOrArray as $value) {
if(!isEmpty($value)) {
return false;
}
}
return true;
}
return !strlen($stringOrArray); // this properly checks on empty string ('')
}
If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
foreach($ary as $value){
if($value == NULL){
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return true;
}else{
return false;
}
}else{
if($null_count > 0){
return true;
}else{
return false;
}
}
}
$test = array_empty($test_ary, $full_null=true);
echo $test;
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
echo "empty array";
}
Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise.
Short circuits.
function has_values($var) {
if (is_array($var)) {
if (empty($var)) return FALSE;
foreach ($var as $val) {
if(has_values($val)) return TRUE;
}
return FALSE;
}
return TRUE;
}
Here's a good utility function that will return true (1) if the array is empty, or false (0) if not:
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
For example, given a multidimensional array:
$products = array(
'product_data' => array(
0 => array(
'title' => '',
'description' => null,
'price' => '',
),
),
);
You'll get a true value returned from is_array_empty(), since there are no values set:
var_dump( is_array_empty($products) );
View this code interactively at: http://codepad.org/l2C0Efab
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues you can decide if values such 0 (number zero), '' (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.
array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray).

Categories