Finding for string in an Array - php

My problem is basically, I will be trying to get data from a table called, 'rank' and it will have data formatted like, "1,2,3,4,5" etc to grant permissions. So Basically I am trying to make it an array and find if one number is there in the array. Basically making it an array is not working. How would I get this done? Here is my code below:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = array($ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>
This code returns false, while it should return true. This is just a basic algorithm.
The print_r Display:
Array ( [0] => 1,2,3,4,5 )

If you know for sure your delimiter is a comma, try this:
$ranks = explode(',',$rank);
where $rank is your string.

That's simple, you explode the $ranks variable by comma ,:
$ranks = "1,2,3,4,5";
$uRanks = explode(',',$ranks);
//$uRanks would now be array(1,2,3,4,5);
if(in_array($rank, $uRanks)) {
//..rest of your code

You should:
$uRanks = explode(',', $ranks);
instead of:
$uRanks = array($ranks);
to make this as array.

Problem solved. I used the explode function instead like this:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = explode(',', $ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>

Related

PHP: How to get last array element in one array

i am trying to create function to check if array element is the last array element in one array. Original array looks like:
array(1001,
1002,
array('exam'=>true, 'index'=>10),
1003,
1004,
1005,
array('exam'=>true, 'index'=>20),
1006,
1007,
array('exam'=>true, 'index'=>30),
1008,
1009
)
I this case to prove if "array('exam'=>true, 'index'=>30)" is the last.
I have index position of that element, but I do not know how to check if that is the last array element.
function is_last_exam_in_survey($array, $exam_position) {
foreach($array as $element) {
if(!is_numeric($element) {
// check if that is the last array element in array
//return true;
} else {
// return false;
}
}
}
I would be grateful for any advice:)
function get_last_exam_in_survey($array) {
$last = null;
foreach($array as $element) {
if(is_array($element) && !empty($element['exam'])) {
$last = $element;
}
}
return $last;
}
function is_last_exam_in_survey($array, $exam_position) {
$last_exam = get_last_exam_in_survey($array);
return !empty($last_exam) && ($last_exam['index']==$exam_position);
}
I think this would be the quickest solution:
function is_last_exam_in_survey($array, $exam_position) {
$last_index = array_key_last( $array );
if( $exam_position == $last_index ){
return true;
}else{
return false;
}
}
You can still change the conditional statement if you are trying to compare values from the last element, for example:
if( isset($last_index['index']) && $exam_position == $last_index['index'] ){
Also, if you want to get the latest array value instead of key, you could use this:
$last_index = end( $array );
I would reverse the array, and look for the first element. Something like:
function is_last_exam_in_survey($array, $exam_position) {
foreach(array_reverse($array) as $element) {
if(!is_numeric($element) {
return $element['index'] === $exam_position;
}
}
return false;
}
Seems like the most efficient and simplest solution to me.
this solution avoid loop. at first we find out the last index of array.Then we use is_array() function for check the last element is array or not.
function get_last_exam_in_survey(array $arr)
{
$lastOfset = count($arr) - 1;
if(is_array($arr[$lastOfset])){
return true;
}else{
return false;
}
}
I think you can use array_column function to do that
function is_last_exam_in_survey($array,$exam_position){
$ac = array_column($array, 'index'); // return array(10,20,30)
$la = $ac[count($ac) - 1]; // 30
foreach ($array as $element) {
if (!is_numeric($element)) {
// check if $element['index'] === 30
if($element['index'] === $la){
return true;
}
}
}
}
How about using array_slice to extract the values in the array that are after the position you are looking at, then array_filter to remove any values that are not arrays. If there are any values left, then the entry you are looking at is not the last array entry in the array.
This may not be very efficient if you are calling it a lot of times with a large array. It may be better to rethink the way the data is stored or loaded into the array.
function is_last_exam_in_survey($array, $exam_position)
{
return isset($array[$exam_position])
&& is_array($array[$exam_position])
&& !array_filter(array_slice($array, $exam_position + 1), 'is_array');
}

PHP check if a variable is LIKE an item in an array using in_array

I am creating this array with the below code:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
}
and i want to check if any item inside the array is LIKE a variable. I have this so far:
if(in_array($data[6], $ignored)) {
but I'm not sure what to do with the LIKE
in_array() doesn't provide this type of comparison. You can make your own function as follows:
<?php
function similar_in_array( $sNeedle , $aHaystack )
{
foreach ($aHaystack as $sKey)
{
if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
{
return true;
}
}
return false;
}
?>
You can use this function as:
if(similar_in_array($data[6], $ignored)) {
echo "Found"; // ^-search ^--array of items
}else{
echo "Not found";
}
Function references:
stripos()
strtolower()
in_array()
Well, like is actually from SQL world.
You can use something like this:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
//do what you want...
}
}
UPDATE: Well, I found this answer, may be it's what you need:
Php Search_Array using Wildcard
Here is a way to do it that can be customized fairly easily, using a lambda function:
$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');
while ($word = array_shift($otherwords)) {
print_r(array_filter($words, like_word($word)));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
http://codepad.org/yAyvPTIq
To add different checks, simply add more conditions to the return. To do it in a single function call:
while ($word = array_shift($otherwords)) {
print_r(find_like_word($word, $words));
}
function find_like_word($word, $words) {
return array_filter($words, like_word($word));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}

PHP Function that can return value from an array key a dynamic number of levels deep

Using PHP, I would like to write a function that accomplishes what is shown by this pseudo code:
function return_value($input_string='array:subArray:arrayKey')
{
$segments = explode(':',$input_string);
$array_depth = count(segments) - 1;
//Now the bit I'm not sure about
//I need to dynamically generate X number of square brackets to get the value
//So that I'm left with the below:
return $array[$subArray][$arrayKey];
}
Is the above possible? I'd really appreciate some pointer on how to acheive it.
You can use a recursive function (or its iterative equivalent since it's tail recursion):
function return_value($array, $input_string) {
$segments = explode(':',$input_string);
// Can we go next step?
if (!array_key_exists($segments[0], $array)) {
return false; // cannot exist
}
// Yes, do so.
$nextlevel = $array[$segments[0]];
if (!is_array($nextlevel)) {
if (1 == count($segments)) {
// Found!
return $nextlevel;
}
// We can return $nextlevel, which is an array. Or an error.
return false;
}
array_shift($segments);
$nextsegments = implode(':', $segments);
// We can also use tail recursion here, enclosing the whole kit and kaboodle
// into a loop until $segments is empty.
return return_value($nextlevel, $nextsegments);
}
Passing one object
Let's say we want this to be an API and pass only a single string (please remember that HTTP has some method limitation in this, and you may need to POST the string instead of GET).
The string would need to contain both the array data and the "key" location. It's best if we send first the key and then the array:
function decodeJSONblob($input) {
// Step 1: extract the key address. We do this is a dirty way,
// exploiting the fact that a serialized array starts with
// a:<NUMBEROFITEMS>:{ and there will be no "{" in the key address.
$n = strpos($input, ':{');
$items = explode(':', substr($input, 0, $n));
// The last two items of $items will be "a" and "NUMBEROFITEMS"
$ni = array_pop($items);
if ("a" != ($a = array_pop($items))) {
die("Something strange at offset $n, expecting 'a', found {$a}");
}
$array = unserialize("a:{$ni}:".substr($input, $n+1));
while (!empty($items)) {
$key = array_shift($items);
if (!array_key_exists($key, $array)) {
// there is not this item in the array.
}
if (!is_array($array[$key])) {
// Error.
}
$array = $array[$key];
}
return $array;
}
$arr = array(
0 => array(
'hello' => array(
'joe','jack',
array('jill')
)));
print decodeJSONblob("0:hello:1:" . serialize($arr));
print decodeJSONblob("0:hello:2:0" . serialize($arr));
returns
jack
jill
while asking for 0:hello:2: would get you an array { 0: 'jill' }.
you could use recursion and array_key_exists to walk down to the level of said key.
function get_array_element($key, $array)
{
if(stripos(($key,':') !== FALSE) {
$currentKey = substr($key,0,stripos($key,':'));
$remainingKeys = substr($key,stripos($key,':')+1);
if(array_key_exists($currentKey,$array)) {
return ($remainingKeys,$array[$currentKey]);
}
else {
// handle error
return null;
}
}
elseif(array_key_exists($key,$array)) {
return $array[$key];
}
else {
//handle error
return null;
}
}
Use a recursive function like the following or a loop using references to array keys
<?php
function lookup($array,$lookup){
if(!is_array($lookup)){
$lookup=explode(":",$lookup);
}
$key = array_shift($lookup);
if(!isset($array[$key])){
//throw exception if key is not found so false values can also be looked up
throw new Exception("Key does not exist");
}else{
$val = $array[$key];
if(count($lookup)){
return lookup($val,$lookup);
}
return $val;
}
}
$config = array(
'db'=>array(
'host'=>'localhost',
'user'=>'user',
'pass'=>'pass'
),
'data'=>array(
'test1'=>'test1',
'test2'=>array(
'nested'=>'foo'
)
)
);
echo "Host: ".lookup($config,'db:host')."\n";
echo "User: ".lookup($config,'db:user')."\n";
echo "More levels: ".lookup($config,'data:test2:nested')."\n";
Output:
Host: localhost
User: user
More levels: foo

extract values found in array from string

I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }

Getting a value into multidimensional array from a list of indexes (array too)

I'm looking for a nice way of doing the magicFunction():
$indexes = array(1, 3, 0);
$multiDimensionalArray = array(
'0',
array('1-0','1-1','1-2',array('2-0','2-1','2-2')),
array('1-4','1-5','1-6')
);
$result = magicFunction($indexes, $multiDimensionalArray);
// $result == '2-0', like if we did $result = $multiDimensionalArray[1][3][0];
Thanks.
You can solve this recursively.
$indexes = array(1, 3, 0);
$multiDimensionalArray = array(
'0',
array('1-0','1-1','1-2',array('2-0','2-1','2-2')),
array('1-4','1-5','1-6')
);
$result = magicFunction($indexes, $multiDimensionalArray);
function magicFunction($indices, $array) {
// Only a single index is left
if(count($indices) == 1) {
return $array[$indices[0]];
} else if(is_array($indices)) {
$index = array_shift($indices);
return magicFunction($indices, $array[$index]);
} else {
return false; // error
}
}
print $result;
This function will go down the $multiDimensionalArray as long as there are indices available and then return the last value accesses by the index. You will need to add some error handling though, e.g. what happens if you call the function with $indexes = array(1,2,3,4);?
This is a recursive version. Will return null if it cannot find a value with the given index route.
function magicFunction($indexes, $array) {
if (count($indexes) == 1) {
return isset($array[$indexes[0]]) ? $array[$indexes[0]] : null;
} else {
$index=array_shift($indexes);
return isset($array[$index]) ? magicFunction($indexes, $array[$index]) : null;
}
}
You can just step trough based on your keys (no need to do any recursion, just a simple foreach):
$result = &$multiDimensionalArray;
foreach($indexes as $index)
{
if (!isset($result[$index]))
break; # Undefined index error
$result = &$result[$index];
}
If you put it inside a function, then it won't keep the reference if you don't want to. Demo.
I think something like this should do the trick for you.
function magicFuntion($indexes, $marray)
{
if(!is_array($indexes) || count($indexes) == 0 || !is_array($marray))
return FALSE;
$val = '';
$tmp_arr = $marray;
foreach($i in $indexes) {
if(!is_int($i) || !is_array($tmp_arr))
return FALSE;
$val = $tmp_arr[$i];
$tmp_arr = $tmp_arr[$i];
}
return $val;
}
Try this :P
function magicFunction ($indexes,$mdArr){
if(is_array($mdArr[$indexes[0]] && $indexes)){
magicFunction (array_slice($indexes,1),$mdArr[$indexes[0]]);
}
else {
return $mdArr[$indexes[0]];
}
}
My own attempt ; found it simpler by not doing it recursively, finally.
function magicFunction($arrayIndexes, $arrayData)
{
if (!is_array($arrayData))
throw new Exception("Parameter 'arrayData' should be an array");
if (!is_array($arrayIndexes))
throw new Exception("Parameter 'arrayIndexes' should be an array");
foreach($arrayIndexes as $index)
{
if (!isset($arrayData[$index]))
throw new Exception("Could not find value in multidimensional array with indexes '".implode(', ', $arrayIndexes)."'");
$arrayData = $arrayData[$index];
}
return $arrayData;
}
Exceptions may be somewhat "violent" here, but at least you can know exactly what's going on when necessary.
Maybe, for sensitive hearts, a third $defaultValue optional parameter could allow to provide a fallback value if one of the indexes isn't found.

Categories