String starts with a defined set of words - php

How to know if a given string starts with a defied set of words?
$allowed = array("foo", "bar");
pseudocode:
$boolean = somefunction($allowed,'food');
$boolean should be TRUE

function doesStringStartWith($string, $startWithOptions)
{
foreach($startWithOptions as $option)
{
if(substr($string, 0, strlen($option)) == $option) // comment this for case-insenstive
// uncomment this for case-insenstive: if(strtolower(substr($string, 0, strlen($option))) == strtolower($option))
{
return true;
}
}
return false;
}
$result = doesStringStartWith('food', array('foo', 'bar'));

function somefunction($allowed, $word) {
$result = array_filter(
$allowed,
function ($value) use ($word) {
return strpos($word, $value) === 0;
}
);
return (boolean) count($result);
}
$boolean = somefunction($allowed,'food');

If you know that all of your prefixes are the same length you could do this:
if ( in_array( substr($input,0,3), $allowed ) {
// your code
}

I came up with the following function:
function testPos($allowed,$s) {
$a = 0;
while($a < count($allowed)) {
if(strpos($s,$allowed[$a]) === 0) {
return true;
}
$a++;
}
}
Now you can try:
$allowed = array('foo','bar');
echo testPos($allowed,'food');

Related

PHP : How to remove a duplicate array item ONCE

I have an array:
$arr1 = [1,2,2,3,3,3];
Is there any method by which I can delete a duplicate value once like,
some_function($arr1,3);
which gives me the ouput $arr1 = [1,2,2,3,3]
As per the comment, check if there are more than one of the element you're searching for, then find and remove one of them.
function remove_one_duplicate( $arr, $target ) {
if( count( array_keys( $arr, $target ) ) > 1 ) {
unset( $arr[array_search( $target, $arr )] );
}
return $arr;
}
This should work...
function removeduplicate($myarray,$needle) {
if (($nmatches = count($matches = array_keys($myarray,$needle))) >= 2) {
for ($i=0; $i<$nmatches; $i++) {
if ($matches[$i+1] == (1+$matches[$i])) {
array_splice($myarray,$matches[$i],1);
break;
}
}
}
return $myarray;
}
To use the function...
$arr1 = [1,2,2,3,3,3,4,7,3,3];
$newarray = removeduplicate($arr1,3)
print_r($newarray);
EDITED:
If you want the function to modify your original array directly, you can do it (the function will return true if a character has been removed or false if not)...
function removeduplicate(&$myarray,$needle) {
if (($nmatches = count($matches = array_keys($myarray,$needle))) >= 2) {
for ($i=0; $i<$nmatches; $i++) {
if ($matches[$i+1] == (1+$matches[$i])) {
array_splice($myarray,$matches[$i],1);
return true;
}
}
}
return false;
}
So, now you can do...
$arr1 = [1,2,2,2,2,2,3,3,3,4,2,2];
removeduplicate($arr1,2);
print_r($arr1);
This function will copy the array skipping only the second instance of the specified element.
function removeOnce($array, $elem) {
$found = 0;
$result = [];
foreach ($array as $x) {
if ($x == $elem && (++$found) == 2) {
continue;
}
$result[] = $x;
}
return $result;
}

Remove duplicate values on an array with a condition in PHP

I want to remove some duplicate values on an array, but there is a condition that the script has to ignore the array that contains a specific word.
Below code is adapted from PHP: in_array.
$array = array( 'STK0000100001',
'STK0000100002',
'STK0000100001', //--> This should be remove
'STK0000100001-XXXX', //--> This should be ignored
'STK0000100001-XXXX' ); //--> This should be ignored
$ignore_values = array('-XXXX');
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
The function to make the array unique is:
function make_unique($array, $ignore) {
$i = 0;
while($values = each($array)) {
if(!in_array($values[1], $ignore)) {
$dupes = array_keys($array, $values[1]);
unset($dupes[0]);
foreach($dupes as $rmv) {
$i++;
}
}
}
return $i;
}
I have tried to use if(!in_array(str_split($values[1]), $ignore)) ... but it just the same.
The array should become like:
STK0000100001
STK0000100002
STK0000100001-XXXX
STK0000100001-XXXX
How to do that?
Try this one, just remove the print_r(); inside the function when using in production
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
function make_unique($array, $ignore) {
$array_hold = $array;
$ignore_val = array();
$i = 0;
foreach($array as $arr) {
foreach($ignore as $ign) {
if(strpos($arr, $ign)) {
array_push( $ignore_val, $arr);
unset($array_hold[$i]);
break;
}
}
$i++;
}
$unique_one = (array_unique($array_hold));
$unique_one = array_merge($unique_one,$ignore_val);
print_r($unique_one);
return count($array) - count($unique_one);
}
This should work for >= PHP 5.3.
$res = array_reduce($array, function ($res, $val) use ($ignore_values) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
return $res;
}, array()
);
Otherwise
$num_of_duplicates = 0;
$res = array();
foreach ($array as $val) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$num_of_duplicates++;
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
}
Edit: Added duplicate count to the second snippet.

PHP function to check if the number belongs to the interval

There is an array:
$bounds = array([0]=>array('lower'=>2,'upper'=>5),
[1]=>array('lower'=>0,'upper'=>3));
and a variable:
$val = 4;
Is there any PHP function that can say whether $val belongs to any interval defined by 'lower' and 'upper' bounds in $bounds array? In this example 4 belongs to the 1st interval [2; 5]. So, the answer should be 'true'.
I don't think there is a built-in function to do this.
However, you can do it with a foreach statement:
function check_interval($bounds, $val) {
foreach ($bounds as $array) {
if($array['lower'] <= $val && $array['upper'] >= $val)
return true;
}
return false;
}
I'm not aware of any. You'll probably have to code it. Something like this will do:
function isFromInterval($bounds, $val) {
foreach ($bounds as $value) {
if ($val >= $value['lower'] && $val <= $value['upper']) {
return true;
}
}
return false;
}
No.
You would have to make a loop for the array like this
$val = 4;
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val <= $data['upper'] AND $val >= $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
// found something
// $bounds[$key_id] is your result in the array
} else {
// found nothing
}
As a function
function find_range($bounds=array(), $val=0, $return_key=TRUE){
if(is_array($bounds) === FALSE){
$bounds = array();
}
if(is_numeric($val) === FALSE){
$val = 0;
}
if(is_bool($return_key) === FALSE){
$return_key = TRUE;
}
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val < $data['upper'] AND $val > $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
return ($return_key === TRUE ? $key_id : TRUE);
} else {
return FALSE;
}
}
No, but you can do:
$bounds = array(3=>array('lower'=>2,'upper'=>5),
4=>array('lower'=>0,'upper'=>3));
$val = 4;
foreach($bounds as $num => $bound){
if(max($bound) >= $val && $val >= min($bound)){
echo $num;
}
}

Check if array key exists [duplicate]

I have a multidimensional array. I need a function that checks if a specified key exists.
Let's take this array
$config['lib']['template']['engine'] = 'setted';
A function should return true when I call it with:
checkKey('lib','template','engine');
//> Checks if isset $config['lib']['template']['engine']
Note that my array isn't only 3 dimensional. It should be able to check even with only 1 dimension:
checkKey('genericSetting');
//> Returns false becase $c['genericSetting'] isn't setted
At the moment I am using an awful eval code, I would like to hear suggest :)
function checkKey($array) {
$args = func_get_args();
for ($i = 1; $i < count($args); $i++) {
if (!isset($array[$args[$i]]))
return false;
$array = &$array[$args[$i]];
}
return true;
}
Usage:
checkKey($config, 'lib', 'template', 'engine');
checkKey($config, 'genericSetting');
I created the following two functions to do solve the same problem you are having.
The first function check is able to check for one/many keys at once in an array using a dot notation. The get_value function allows you to get the value from an array or return another default value if the given key doesn't exist. There are samples at the bottom for basic usage. The code is mostly based on CakePHP's Set::check() function.
<?php
function check($array, $paths = null) {
if (!is_array($paths)) {
$paths = func_get_args();
array_shift($paths);
}
foreach ($paths as $path) {
$data = $array;
if (!is_array($path)) {
$path = explode('.', $path);
}
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0') {
$key = intval($key);
}
if ($i === count($path) - 1 && !(is_array($data) && array_key_exists($key, $data))) {
return false;
}
if (!is_array($data) || !array_key_exists($key, $data)) {
return false;
}
$data =& $data[$key];
}
}
return true;
}
function get_value($array, $path, $defaultValue = FALSE) {
if (!is_array($path))
$path = explode('.', $path);
foreach ($path as $i => $key) {
if (is_numeric($key) && intval($key) > 0 || $key === '0')
$key = intval($key);
if ($i === count($path) - 1) {
if (is_array($array) && array_key_exists($key, $array))
return $array[$key];
else
break;
}
if (!is_array($array) || !array_key_exists($key, $array))
break;
$array = & $array[$key];
}
return $defaultValue;
}
// Sample usage
$data = array('aaa' => array(
'bbb' => 'bbb',
'ccc' => array(
'ddd' => 'ddd'
)
));
var_dump( check($data, 'aaa.bbb') ); // true
var_dump( check($data, 'aaa.bbb', 'aaa.ccc') ); // true
var_dump( check($data, 'zzz') ); // false
var_dump( check($data, 'aaa.bbb', 'zzz') ); // false
var_dump( get_value($data, 'aaa.bbb', 'default value') ); // "bbb"
var_dump( get_value($data, 'zzz', 'default value') ); // "default value"

Define multiple needles using stripos

How can i define multiple needles and still perform the same actions below. Im trying to define extra keywords such as numbers, numerals, etc... as of now i have to create a duplicate if loop with the minor keyword change.
if (stripos($data, 'digits') !== false) {
$arr = explode('+', $data);
for ($i = 1; $i < count($arr); $i += 2) {
$arr[$i] = preg_replace('/\d/', '', $arr[$i]);
}
$data = implode('+', $arr);
}
Create a function that loops through an array?
function check_matches ($data, $array_of_needles)
{
foreach ($array_of_needles as $needle)
{
if (stripos($data, $needle)!==FALSE)
{
return true;
}
}
return false;
}
if (check_matches($data, $array_of_needles))
{
//do the rest of your stuff
}
--edit added semicolon
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
Usage:
$array = array('1','2','3','etc');
if (strposa($data, $array)) {
$arr = explode('+', $data);
for ($i = 1; $i < count($arr); $i += 2) {
$arr[$i] = preg_replace('/\d/', '', $arr[$i]);
}
$data = implode('+', $arr);
} else {
echo 'false';
}
function taken from https://stackoverflow.com/a/9220624/1018682
Though the previous answers are correct, but I'd like to add all the possible combinations, like you can pass the needle as array or string or integer.
To do that, you can use the following snippet.
function strposAll($haystack, $needles){
if(!is_array($needle)) $needles = array($needles); // if the $needle is not an array, then put it in an array
foreach($needles as $needle)
if( strpos($haystack, $needle) !== False ) return true;
return false;
}
You can now use the second parameter as array or string or integer, whatever you want.

Categories