Using explode('<br>',$String) I have an Array1 with sub-Strings.I want to use an Array2 as needles to loop through Array1 and if a Sub-String is found return Array2 values.
Example:
$Array1 { [0]=> string(3) "red"
[1]=> string(4) "Blue"
[3]=> string(5) "Black" };
$Array2 [
'red' => "Red",
'Yellow' => "Yellow"];
What is the best method/function to approach this task. In the example above the Array1 ( Haystack) has a substring "red" , I want to be able to define Key => values in Array2 to use as needles and when for example a certain Key is found return its value.
// Output above
"Red"
Thanks
You can do it with a simple foreach loop
function getColorOrSomething(&$array1, &$array2){
foreach($array2 as $key=>$value)
if(in_array($key, $array1))
return $value;
return null; //no match found
}
and then of course call the function with the 2 arrays
$selected = getColorOrSomething($array1, $array2);
You can use a nested loop like this:
$key = "";
$value = "";
foreach( $Array1 as $ar1 ) {
foreach( $Array2 as $ak2=>ar2 ) {
if( preg_match("/" . $ak2 . "/", $ar1) ) {
$key = $ak2;
break;
}
if( $key != "" ) {
$value = $ar1;
break;
}
}
}
echo "Key: " . $key . " & Value: " . $value;
Like so..
Related
Is it possible to search an array for a given value and return all the indexes at which the value was found? So for this array:
["Red","Green","Red","Blue"]
I need
[0,2]
with regard to a search for "Red". Searching for "Yellow" in this case would return an empty array.
You can use like this:
$array = ["Red","Green","Red","Blue"];
$output = array_keys($array, "Red");
The $output will be [0,2]
I think this should work:
$input = ["Red","Green","Red","Blue"];
$x = "Red";
$keys = array_keys(array_filter($input, function ($v) use ($x) { return $v === $x;}));
You can iterate the array with foreach:
foreach($input_arr as $key => $value){
if($value == 'Red'){
needed_key_arr[] = $key;
}
}
Also, if you can have an array of values you what to search use:
$lookup_arr = ['Red', 'Green'];
foreach($input_arr as $key => $value){
if(in_array($value, $lookup_arr)){
needed_key_arr[] = $key;
}
}
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) { // filter the first array
return array_filter($valueToSearchFor, function ($val) use ($val1) { // use the first array's value
return $val == $val1; // compare them and then return them
});
}));
var_dump($keys) // array(2) { [0]=> int(0) [1]=> int(2) }
First we filter the array then take the values from the first filter to another filter then we match the arrays and we return them. This works for multiple values too.
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red", "Blue"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) {
return array_filter($valueToSearchFor, function ($val) use ($val1) {
return $val == $val1;
});
}));
var_dump($keys) // array(3) { [0]=> int(0) [1]=> int(2) [2]=> int(3) }
There are two arrays:
$arr1 = ['word', 'tech', 'care', 'kek', 'lol', 'wild', 'regex'];
$arr2 = ['ord', 'ek', 'ol', 'ld', 'gex', 'ss'];
The number of elements in the second array is less than or equal to the first array.
Sort out the first array and the second array, if the elements of the second array are contained at the end of the elements of the first array, sort the array in this form:
Array
(
[0] => w_ord
[1] => tech
[2] => care
[3] => k_ek
[4] => l_ol
[5] => wi_ld
[6] => re_gex
)
Important: the elements of the second array are never repeated, and can go in any order. If in the second element there is no end of the element of the first array, then set the value of the element of the first array.
I do this:
foreach($arr2 as $val) {
$strrepl[$val] = "_".$val;
}
foreach($arr1 as $key => $val) {
$arr3[$key] = str_replace(array_keys($strrepl), $strrepl, $val);
}
print_r($arr3);
But I'm not sure that this is the right approach, what will you advise?
Hmm, let's see ... purely functional 'cause you know :D
function ends($str) {
return function($suffix) use($str) {
return mb_strlen($str) >= mb_strlen($suffix)
&& mb_substr($str, mb_strlen($suffix) * -1) === $suffix;
};
}
$result = array_map(function($item) use($arr2) {
$filter = ends($item);
$suffixes = array_filter($arr2, $filter);
if (empty($suffixes)) {
return $item;
}
// This only cares about the very first match, but
// is easily adaptable to handle all of them
$suffix = reset($suffixes);
return mb_substr($item, 0, mb_strlen($suffix) * -1) . "_{$suffix}";
}, $arr1);
Surprisingly, this one was quite fun to execute.
Since you went very specific on end of the element, I decided to use RegEx for that.
Here is my approach:
$arr1 = ['word', 'tech', 'care', 'kek', 'lol', 'wild', 'regex'];
$arr2 = ['ord', 'ek', 'ol', 'ld', 'gex', 'ss'];
foreach ($arr2 as $find) {
foreach ($arr1 as $key => $element) {
$arr1[$key] = preg_replace('/' . $find . '$/', '_' . $find, $element);
}
}
For every element of the second array (since they are not repeated), I go through every element of the first array and check if the value can be found at the end of the element of the second array using the $ anchor from RegEx which forces it to look it from the end of the string.
This way the $arr1 will have exactly what you expect.
[Edit]
Following the scape suggestion from #aefxx and improving variable names.
You can use preg_grep which is regex on arrays.
This code will also make sure it can output more than one matching word from $arr1.
$arr1 = ['word', 'chord', 'tech', 'care', 'kek', 'lol', 'wild', 'regex'];
$arr2 = ['ord', 'ek', 'ol', 'ld', 'gex', 'ss'];
$keys=[];
foreach($arr2 as $val){
$matches = preg_grep("/.+" . preg_quote($val) . "/", $arr1);
$keys = array_merge($keys, array_keys($matches)); // save keys of matched words
foreach($matches as $key => $m) $new[$val][] = str_replace($val, "_$val", $arr1[$key]);
}
$new['unmatched'] = array_diff_key($arr1, array_flip($keys)); // add unmatched words
var_dump($new);
Output:
array(6) {
["ord"]=>
array(2) {
[0]=>
string(5) "w_ord"
[1]=>
string(6) "ch_ord"
}
["ek"]=>
array(1) {
[0]=>
string(4) "k_ek"
}
["ol"]=>
array(1) {
[0]=>
string(4) "l_ol"
}
["ld"]=>
array(1) {
[0]=>
string(5) "wi_ld"
}
["gex"]=>
array(1) {
[0]=>
string(6) "re_gex"
}
["unmatched"]=>
array(2) {
[2]=>
string(4) "tech"
[3]=>
string(4) "care"
}
}
https://3v4l.org/gfUea
You can try this.I think it is easy to understand :
$arr1=['word','tech','care','kek','lol','wild','regex'];
$arr2=['ord','ek','ol','ld','gex','ss'];
foreach($arr1 as $key=>$fullword){
foreach($arr2 as $substr){
$arr1[$key]=preg_replace('/' . $substr . '$/', '_' . $substr, $fullword,-1,$count);
if($count) break;
}
}
i go throught the array of fullword and as soon as i find a match i stop the search.
Another approach can be to create complex regex beforehand (using implode and preg_quote for safety) and use it for replacement inside array_map callback:
$arr1 = ['word', 'tech', 'care', 'kek', 'lol', 'wild', 'regex'];
$arr2 = ['ord', 'ek', 'ol', 'ld', 'gex', 'ss'];
$regex = '/(' . implode('|', array_map('preg_quote', $arr2)) . ')$/';
$result = array_map(function ($word) use ($regex) {
return preg_replace($regex, '_$1', $word);
}, $arr1);
Here is the demo.
i have array
Example :
array(3) { [0]=> string(6) "{what}" [1]=> string(5) "[why]" [2]=> string(5) "(how)" }
and then how to take array with specific char ("{") ?
Is my understanding here correct? You want to get items in array that has a "{" Character. Then why not just loop over it and check the item if it has that character and push it in a new array.
$array_with_sp_char = array();
foreach ($arr_items as $item) {
if (strpos($item, '{') !== FALSE) {
array_push($array_with_sp_char, $item);
}
}
Just iterate through your array and filter out the values you are interested in, in your case i guess it's the values that contain the Char "{"
A possible implementation:
$result = array_filter($your_array, function($value) {
return preg_match('/{/', $value);
});
Use a combination of array_filter and strpos:
$array = [
"{what}",
"[why]",
"(how)"
];
$array = array_filter($array, function($value) {
return strpos($value, '{') !== false;
});
print_r($array);
That will give you:
Array
(
[0] => {what}
)
I have an array in PHP and I don't know how to delete all the elements from every array element from certain character on, icluding that character. Is there a way to do this?
array(1092) {
["Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite"]=>
int(124)
}
In my example I want to delete all text from "#####", including "#####" to the end, foreach array element. Is this possible? Or is there a PHP function for this?
UPDATE
My result should look like this:
array(1092) {
["Piper;Rosii;Sare;Test;Vinete]=>
int(124)
}
You can use array_walk to apply the substr and strpos to each element:
$array = [
'23845637;54634;345;3453345;#####morestuff',
'234234#####34596078345j34534534',
'34343245dfg#####asdfsadf;23452345;sdfsdf;345345'
];
array_walk($array, function(&$value, $key) {
$value = substr($value, 0, strpos($value, '#####'));
});
var_dump($array);
Will result in:
array(3) {
[0]=>
string(27) "23845637;54634;345;3453345;"
[1]=>
string(6) "234234"
[2]=>
string(11) "34343245dfg"
}
This will modify the original array.
For each element in the array, we search for the position of '#####' in the string and only take the part from 0 to the position in the string where '#####' occurs.
This will do that by looping through the array exploding the key by ##### and adding it to a new array. I did it in a loop in case your array is bigger than 1
<?php
$oldArray = array("Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite" => 124);
$newArray = array();
foreach ($oldArray as $key => $row) {
$newKey = explode('#####', $key);
$newArray[$newKey[0]] = $row;
}
var_dump($newArray);
You can use substr and strpos to add the new entry and then unset the old entry in the array like this example:
$array = array(
"Piper;Rosii;Sare;Test;Vinete#####Piper ->Negru;Rosii ->Călite;Sare ->De masă, grunjoasă;Vinete ->Prăjite" => 124
);
foreach ($array as $key => $value) {
$array[substr($key, 0, strpos($key, '#####'))] = $value;
unset($array[$key]);
}
var_dump($array);
Will result in:
array(1) {
["Piper;Rosii;Sare;Test;Vinete"]=>
int(124)
}
I have 30 lines of text and explode into arrays separate by "\n". the result as follows:
[1]=> string(121) "In recent years, the rapid growth"
[2]=> string(139) "information technology has strongly enhanced computer systems"
[3]=> string(89) "both in terms of computational and networking capabilities"
[4]=> string(103) "-------------------------"
[5]=> string(103) "these novel distributed computing scenarios"
.
.
[30]=> string(103) "these computer safety applications. end"
in this case, i need to remove all arrays below "-------------" and produce output as follows:
[1]=> string(121) "In recent years, the rapid growth"
[2]=> string(139) "information technology has strongly enhanced computer systems"
[3]=> string(89) "both in terms of computational and networking capabilities"
any idea how to do this? thanks.
solution of the problem by Michael
$i = 0;
$new_arr = array();
while ($array[$i] != "-------------------------") {
// Append lines onto the new array until the delimiter is found
$new_arr[] = $array[$i];
$i++;
}
print_r($new_arr);
Best solution:
Use array_search() and then truncate the array with array_splice():
$key = array_search("-------------------------", $array);
array_splice($array, $key);
Obvious solution:
You can loop over it copying the output to a new array. First example that comes to mind:
$i = 0;
$new_arr = array();
while ($array[$i] != "-------------------------") {
// Append lines onto the new array until the delimiter is found
$new_arr[] = $array[$i];
$i++;
}
print_r($new_arr);
for example
function getMyArray( $array ){
$myArray = array();
foreach( $array as $item ){
if ( $item == '-------------------------' ){ return $myArray; }
$myArray[] = $line;
}
return $myArray'
}
array_search
and unset
you can also use array_slice
You can use array_search to find the key of where its located.
from PHP.net:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
?>
Once you have the key, you could do:
<?php
while($key < count($array) )
{
$array = unset($array[$key]);
$key++;
}
?>
foreach($array as $key => $value)
{
if($value == '-------------')
break;
else
$new_array[$key]=$value;
}