PHP: check if an element belongs to an array - php

I know PHP 4 and PHP 5 supports a built in function in_array for determining is an element is in an array or not.
But, I am using a prior version of PHP for some reason and wanted to know what is the alternative for it.

Use a custom function. For future compatibility, you could use function_exists to check if the current version of PHP that you're using does indeed have in_array.
function inArray($needle, $haystack)
{
if (function_exists('in_array')) {
return in_array($needle, $haystack);
} else {
foreach ($haystack as $e) {
if ($e === $needle) {
return true;
}
}
return false;
}
}

If you are using something older than PHP 4, foreach will also be unavailable, so you will need to stick with list and each. Also to make in forward compatible, use third parameter for strict comparison:
if (!function_exists('in_array')) {
function in_array($needle, $haystack, $strict = false) {
while (list($key, $item) = each($haystack)) {
if ($strict && $needle === $item) {
return true;
} else if (!$strict && $needle == $item) {
return true;
}
}
return false;
}
}

Without checking what functions were available in what versions, and comparing against the version you are using (we're not php.net encyclopedia's), your best bet is to go back to basics, and just loop through and check.
function in_array($val, $array) {
foreach($array as $a) {
if($a === $val)
return true;
}
return false;
}

You can create your own function to mimic the functionality with
function my_in_array($ar, $val)
{
foreach($ar as $k => $v)
{
if($v == $val) return true;
}
return false;
}
or if you looking for a key
function my_in_array($ar, $val)
{
foreach($ar as $k => $v)
{
if($k == $val) return true;
}
return false;
}

Create your own in array function something like below:
function my_in_array($value, $arr) {
foreach ($arr as $a) {
if ($a == $value) {
return true;
}
}
return false;
}

Related

How to check given value present in nested array in PHP?

I am very new to the PHP, i want to check the value is present inside the associative array,please help me to acheive this thing.
public $array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
foreach($array as $key=>$condition){
if(in_array('myFunction',$array)){
//My logic
}
}
if you know the keys:
if($array['value.details']['type'] === 'myFunction') { }
if you walk through your array:
foreach($array as $key=>$val) {
if(is_array($val) && in_array('myFunction', $val)) {
//
}
}
Your array is mix of string and array, you might also wanna check the array inside your array.
$array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
$query = 'myFunction';
$isPresent = false;
foreach ($array as $data) {
if (gettype($data) === "array") {
foreach ($data as $val) {
if ($val === $query) {
$isPresent = true;
continue;
}
}
} else {
if ($query === $data) {
$isPresent = true;
continue;
}
}
}

PHP: universal recursive array search [duplicate]

This question already has answers here:
Search for a key in an array, recursively
(7 answers)
Closed 8 years ago.
I try to find a value in an array, no matter how deep that array is or what "structure" it may have. But my approach doesn't find all values. I think I get the recursion wrong, but I don't know.
$haystack = array(
'A',
'B' => array('BA'),
'C' => array('CA' => array('CAA')),
'D' => array('DA' => array('DAA' => array('DAAA')))
);
function array_find($needle, array $haystack) {
foreach ($haystack as $value) {
if (is_array($value)) {
if (in_array($needle, $value)) {
return true;
} else {
return array_find($needle, $value);
}
} else {
if ($value == $needle) {
return true;
}
}
}
return false;
}
$find = array('A', 'BA', 'CAA', 'DAAA');
foreach($find as $needle) {
if (array_find($needle, $haystack)) {
echo $needle, " found".PHP_EOL;
} else {
echo $needle, " not found".PHP_EOL;
}
}
Simply change your code to:
function array_find($needle, array $haystack) {
foreach ($haystack as $value) {
if (is_array($value)) {
if (in_array($needle, $value)) {
return true;
} else {
if (array_find($needle, $value)) {
return true;
}
}
} else {
if ($value == $needle) {
return true;
}
}
}
return false;
}
The problem is in your return statement.
I think this can be written more simply:
function array_find($needle, array $haystack) {
foreach ($haystack as $value) {
if (is_array($value)) {
if (array_find($needle, $value)) {
return true;
}
} else {
if ($value == $needle) {
return true;
}
}
}
return false;
}
I do not know whether or not there is a benefit to using in_array rather than just making the recursive call as soon as you determine it is an array.

PHP checking if all inputs were set doesn't function?

So I started using MVC. I don't use a framework. It's just self-practice.
So this is my register part:
protected function _instance()
{
if ($_POST != null)
{
/**
* Validating if forms are not empty
**/
if (self::validateForms())
{
echo 1;
}
else
{
new Error("One of the forums was empty..");
}
}
}
private static function validateForms()
{
$inputs = array (
'username', 'password', 'repassword',
'email', 'password_f', 'repassword_f',
'display'
);
$i = 0;
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
}
Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?
The problem is you are returning within your loop after the first test.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
should be
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
or more concisely
foreach ($inputs as $key)
{
if (!isset($_POST[$key]) || empty($_POST[$key]))
{
return false;
}
}
return true;
You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through. Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}

Comparing in_array values

I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.

Converting keys of an array/object-tree to lowercase

I am currently optimizing a PHP application and found one function being called around 10-20k times, so I'd thought I'd start optimization there:
function keysToLower($obj)
{
if(!is_object($obj) && !is_array($obj)) return $obj;
foreach($obj as $key=>$element)
{
$element=keysToLower($element);
if(is_object($obj))
{
$obj->{strtolower($key)}=$element;
if(!ctype_lower($key)) unset($obj->{$key});
}
else if(is_array($obj) && ctype_upper($key))
{
$obj[strtolower($key)]=$element;
unset($obj[$key]);
}
}
return $obj;
}
Most of the time is spent in recursive calls (which are quite slow in PHP), but I don't see any way to convert it to a loop.
What would you do?
This version doesn't account for associative arrays since my data doesn't have any, but is nearly 10 times faster than the original version. Most of the work was done by Gumbo, the major speedup comes from using references and creating a new object instead of unsetting the old keys.
function &keysToLower(&$obj)
{
if(is_object($obj))
{
$newobj = (object) array();
foreach ($obj as $key => &$val)
$newobj->{strtolower($key)} = keysToLower($val);
$obj=$newobj;
}
else if(is_array($obj))
foreach($obj as &$value)
keysToLower($value);
return $obj;
}
Foreach is using an internal copy that is then traversed. Try it without:
function keysToLower($obj)
{
$type = (int) is_object($obj) - (int) is_array($obj);
if ($type === 0) return $obj;
reset($obj);
while (($key = key($obj)) !== null)
{
$element = keysToLower(current($obj));
switch ($type)
{
case 1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj->{$key});
$key = $keyLowercase;
}
$obj->{$key} = $element;
break;
case -1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj[$key]);
$key = $keyLowercase;
}
$obj[$key] = $element;
break;
}
next($obj);
}
return $obj;
}
Or use references to avoid that a copy is used:
function &keysToLower(&$obj)
{
$type = (int) is_object($obj) - (int) is_array($obj);
if ($type === 0) return $obj;
foreach ($obj as $key => &$val)
{
$element = keysToLower($val);
switch ($type)
{
case 1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj->{$key});
$key = $keyLowercase;
}
$obj->{$key} = $element;
break;
case -1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj[$key]);
$key = $keyLowercase;
}
$obj[$key] = $element;
break;
}
}
return $obj;
}
You might also want to lookup array_change_key_case()
I assume you don't care about casting to array...
function keys_to_lower($o) {
if (is_object($o)) {
$o = (array)$o;
}
if (is_array($o)) {
return array_map('keys_to_lower', array_change_key_case($o));
}
else {
return $o;
}
}
here a example using lambda:
$multiArrayChangeKeyCase = function (&$array) use (&$multiArrayChangeKeyCase) {
$array = array_change_key_case($array);
foreach ($array as $key => $row)
if (is_array($row))
$multiArrayChangeKeyCase($array[$key]);
};
array_combine(array_map("strtolower", array_keys($a)), array_values($a))
A some what late response to a old thread but, there's a native function that does this, you could wrap it up something along these lines.
function setKeyCasing($thing, $case = CASE_LOWER) {
return array_change_key_case((array) $thing, $case);
}

Categories