I want to find the occurrence of a specific letter in array and also want to count the number of values in which it is present.
for example:
<?php
$aa= array (
'sayhello',
'hellostackoverflow',
'ahelloworld',
'foobarbas'
'apple'
);
here if i search for 'o' then it should return 4 as 'o' is present in only four values
try this code this is worked for me.
<?php
$input = preg_quote('o', '~'); // don't forget to quote input string!
$data = array (
'sayhello',
'hellostackoverflow',
'ahelloworld',
'foobarbas',
'apple'
);
$result = preg_grep('~' . $input . '~', $data);
echo count($result); // return the number of element
echo '<pre>';
print_r($result);
exit;
?>
i hope this is working for you.
An array can just be flattened to a string for all intents and purposes.
$occurences = substr_count((string)$aa, 'o');
$occurences will then be 4.
You can use from this structure:
function array_seaech($array, $search)
{
$count = 0;
foreach($array as $key => $value)
{
if(strpos($value, $search))
$count++;
}
return $count;
}
in this structure we check all nodes of an array and check if that string exist or not.
Related
I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);
I have two arrays:
$array_one = array('AA','BB','CC');
And:
$replacement_keys = array
(
""=>null,
"BFC"=>'john',
"ASD"=>'sara',
"CSD"=>'garry'
);
So far I've tried
array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.
My goal is to make a final output:
$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);
In other words to find a matching first letter and than replace the key with the value of the first array.
Any and all help will be highly appreciated.
Here is a solution keeping both $replacement_keys and $array_one intact
$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
$index = array_search(substr($key, 0, 1), $tempArray);
if ($index !== false) {
$new_array[$array_one[$index]] = $replacement_key;
} else {
$new_array[$key] = $replacement_key;
}
}
Here is a link https://3v4l.org/fuHSu
You can approach like this by using foreach with in_array
$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
$split = str_split($k)[0];
$split .= $split;
in_array($split, $a1) ? ($r[$split] = $v) : ($r[$k] = $v);
}
Working example :- https://3v4l.org/ffRWY
So my question might not be the best, so sorry for that.
I have an array with strings and want to write a text with the help of another array using it as the order/key. This is the Input:
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
//var_export($words);
// array (
// 0 => 'I',
// 1 => 'am',
// 2 => 'cool',
// )
I want to use $order as some sort of key to rearrange $words so I can get this Output:
"Cool I am I am cool"
Help is much appreciated, thank you :)
Use the values of $order as the keys for $words.
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
$output = '';
foreach($order as $key) {
$output .= $words[$key] . ' ';
}
echo ucfirst(trim($output));
Demo: https://eval.in/780785
The empty($real_key) is to check if it is the first iteration. Also could be == 0.
I would recommend the use of array_map and join
There is no need for
side-effecting manual iteration using foreach
if statements or ternary (?:) expressions
variable reassignment
string concatenation using .
checking array lengths
Here we go
function map_indexes_to_words ($indexes, $words) {
$lookup = function ($i) use ($words) {
return $words[(int) $i];
};
return join(' ', array_map($lookup, $indexes));
}
$words = ["I","am","cool"];
$order = ["2","0","1","0","1","2"];
echo map_indexes_to_words($order, $words);
// 'cool I am I am cool'
Start with an empty array.
Then loop through the order array and add the word array part to the new string.
$my_string= array();
foreach ( $order as $index ) {
$index = int($index);
$my_string[] = ( isset($words[ $index]) ) ? $words[ $index ] : '' );
}
$my_string = implode(' ', $my_string);
echo my_string;
Iterate over order and use it's values as keys to words; Convert the following code to php it should be pretty simple...
foreach (string orderIndexString in order) {
int orderIndexInt = System.Convert.ToInt16(orderIndexString); // convert string to int
if(orderIndexInt < 0 || orderIndexInt >= words.Length)
continue;
print (words[orderIndexInt]); // either print or add it to another string
}
I'm not sure how to better phrase my question, but here is my situation.
I have an array like the following:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
I need to loop through this array and try to match the first portion of each string in the array
e.g.
$id = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
fetch this string
append "999888" to "122874|876394|120972"
insert this string back to array
}
So the resulting array becomes:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");
Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.
Thanks
Try this:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){
// Get the first characters of the element up to the occurrence of a dash "-" ...
$num = substr($arr, 0, strpos($arr, '-'));
// ...and check if it is equal to $id...
if ($num == $id){
// ...if so, add $random_number to the back of the current array element
$temp_array[$i] .= '|' . $rand_number;
}
}
Output:
Array
(
[0] => 111111-Name1-122874|876394|120972
[1] => 222222-Name2-122874|876394|120972|999888
[2] => 333333-Name3-122874|876394|120972
)
See demo
Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php
You could also using some exploding in this case too:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
// ^ reference
$pieces = explode('|', $line); // explode pipes
$first = explode('-', array_shift($pieces)); // get the first part, explode by dash
if($first[0] == $id) { // if first part is equal to id
$first[2] = $rand_number; // replace the third part with random
$first = implode('-', $first); // glue them by dash again
$line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
}
}
echo '<pre>';
print_r($temp_array);
crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr
$temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as $t){
if(substr(0,6,$t)==$id){
$new[] = $t.'|'.$rand_number;
}else{
$new[] = $t;
}
}
Another version using array_walk
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
$parts = explode('-', $value); // Split parts with '-' so the first part is id
if ($parts[0] == $param['id']){
$parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
$value=implode('-',$parts); //combine the parts back
}
},$params);
print_r($temp_array);
If you just want to append The code becomes much shorter
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
// here check if the first part of the result of explode is ID
// then append the rand_number to the value else append '' to it.
$value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);
Edit: Comments added to code.
Let's say I have a multidimensional array like this:
[
["Thing1", "OtherThing1"],
["Thing1", "OtherThing2"],
["Thing2", "OtherThing3"]
]
How would I be able to count how many times the value "Thing1" occurs in the multidimensional array?
you can use array_search for more information see this http://www.php.net/manual/en/function.array-search.php
this code is sample of this that is in php document sample
<?php
function recursiveArraySearchAll($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
$resultkeys;
while($it->valid()) {
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle
$resultkeys[]=$aIt->key(); //return $aIt->key();
}
$it->next();
}
return $resultkeys; // return all finding in an array
} ;
?>
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
http://www.php.net/manual/en/function.array-keys.php
Try this :
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
echo "<pre>";
$res = array_count_values(call_user_func_array('array_merge', $arr));
echo $res['Thing1'];
Output :
Array
(
[Thing1] => 2
[OtherThing1] => 1
[OtherThing2] => 1
[Thing2] => 1
[OtherThing3] => 1
)
It gives the occurrence of each value. ie : Thing1 occurs 2 times.
EDIT : As per OP's comment : "Which array do you mean resulting array?" - The input array. So for example this would be the input array: array(array(1,1),array(2,1),array(3,2)) , I only want it to count the first values (1,2,3) not the second values (1,1,2) – gdscei 7 mins ago
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$res = array_count_values(array_map(function($a){return $a[0];}, $arr));
echo $res['Thing1'];
function showCount($arr, $needle, $count=0)
{
// Check if $arr is array. Thx to Waygood
if(!is_array($arr)) return false;
foreach($arr as $k=>$v)
{
// if item is array do recursion
if(is_array($v))
{
$count = showCount($v, $needle, $count);
}
elseif($v == $needle){
$count++;
}
}
return $count;
}
Using in_array can help:
$cont = 0;
//for each array inside the multidimensional one
foreach($multidimensional as $m){
if(in_array('Thing1', $m)){
$cont++;
}
}
echo $cont;
For more info: http://php.net/manual/en/function.in-array.php
try this
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$abc=array_count_values(call_user_func_array('array_merge', $arr));
echo $abc[Thing1];
$count = 0;
foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}
If you prefer code brevity zero global scope pollution, you can count every value and access the one count that you do want:
echo array_count_values(array_merge(...$array))['Thing1'] ?? 0;
If you don't want to bother counting values where the count will never be needed, then you can visit leafnodes with array_walk_recursive() and +1 everytime the target value is encountered.
$thing1Count = 0;
array_walk_recursive($array, function($v) use(&$thing1Count) { $thing1Count += ($v === 'Thing1'); });
echo $thing1Count;
Both snippets return 2. Here's a Demo.