I'm currently using this:
foreach($hash_list as $key => $val){
if(in_array($search_this,$hash_list[$key])){
echo 'Found value in key '.$key;
break;
}
}
To find $search_this in this:
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
Is there a better way to find the key for this situation? $hash_list has about 500 arrays with 5 elements each inside.
Deadpool: #Sergey No php built-in function that I'm missing?
I dont think so. But I think it's may be little faster, but I'm not sure
$hash_list = array();
$hash_list["a"] = "dfv8p, hi8o7, d2l9f, qhx13, c7duz";
$hash_list["b"] = "pdsyt, jjivh, nj12b, 19tm2, ltsqp";
$hash_list["c"] = "67s6q, tlwu7, c9p77, 7airj, j7tej";
foreach($hash_list as $key => $val){
if(strpos($hash_list[$key], $search_this) !== false) {
echo 'Found value in key '.$key;
break;
}
}
You can use user build functions like this
function isValueExist($hash_list,$needle){
foreach($hash_list as $val){
if(in_array($needle,array_values($val))) return 1;
}
}
Usage :-
if (isValueExist($hash_list,"d2l9f")){
//DO you things here
}
You can make use of list() too ;)
<?php
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
$searchParam = "67s6q";
while(list($a,$b) = each($hash_list))
{
if(in_array($searchParam,$b))
{
echo "$searchParam found in $a\n";
}
}
OUTPUT :
67s6q found in c
Related
I have loop value with code
foreach($season as $seasons){
echo $seasons->Combined_season ;
}
and the result is 0000000011111111111111111111111222222222222222222222223333333333333333333333344444444444444444444444555555555
How to skip if there same values?
I want the result is
012345
You are looking for "unique" values:
<?php
foreach($season as $seasons){
$result[] = $seasons->Combined_season;
}
echo implode('', array_unique($result));
A somewhat awkward but more memory efficient version would be this:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = $seasons->Combined_season;
}
echo implode('', $result);
And the most efficient variant:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = null;
}
echo implode('', array_keys($result));
All approaches have the advantage that they do not require a conditional in each loop iteration which makes them far more efficient for bigger input sets.
Here an update to answer your additional question:
I mentioned more than once in my comments that the variant 2 and 3 deliver what you are looking for. That you only have to use the values internally instead of imploding them for output.
The following is exactly the third approach from above, the only difference is that I did what I told you before in the comments: use the values instead of imploding them. As far as I can see it delivers exactly what you are looking for:
<?php
foreach($season as $seasons){
$result[$seasons->Combined_season] = null;
}
$value = array_keys($result);
$printedSeasons = [];
foreach($season as $seasons){
if (!in_array($seasons->Combined_season, $printedSeasons)) {
$printedSeasons[] = $seasons->Combined_season;
echo $seasons->Combined_season;
}
}
<?php
$values = [];
foreach($season as $seasons){
if(! in_array($seasons->Combined_season, $values)) {
$values[] = $seasons->Combined_season;
echo $seasons->Combined_season ;
}
}
basically, you store any new value in an array, and before printing a value, you check if it already is in that array.
Using the "array approach" is maybe the best approach. But if your results are sorted like in your example you could use an other approach, with a current value.
$curr_val = '';
foreach($season as $seasons){
if ($seasons->Combined_season != $curr_val){
echo $seasons->Combined_season ;
$curr_val = $seasons->Combined_season ;
}
}
You can use an external variable:
$old_value = '';
foreach($season as $seasons){
$new_value = $seasons->Combined_season;
if($old_value != $new_value)
{
echo $new_value;
$old_value = $new_value;
}
}
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'; }
I have a multiple-array :
$bouton["modify-customer"] = array("fr"=>"liste-client", "en"=>"customer-list");
$bouton["create-customer"] = array("fr"=>"creer-client", "en"=>"create-customer");
$bouton["modify-item"] = array("fr"=>"liste-item", "en"=>"item-list");
$bouton["create-item"] = array("fr"=>"creer-item", "en"=>"create-item");
$bouton["modify-taxes"] = array("fr"=>"liste-taxes", "en"=>"taxes-list");
$bouton["create-taxes"] = array("fr"=>"creer-taxes", "en"=>"create-taxes");
In a page, I have this string : "liste-taxes"
I need to find : "taxes-list"
How can I achieve this task? ...
I know that I need to find the right key here, and it's modify-taxes then I will probably be able to find the other value not the fr one, but the en one.
I know I'm not super-clear and my English is not very good but I hope you guys can help me, I will stay on the site so I will be able to answer your question and talk with you in the futur comments.
Thanks.
You'll want to loop through the array and search for the value like so:
foreach($bouton as $key => $array){
if( in_array("liste-taxes",$array)){
echo $key . PHP_EOL;
echo $bouton[$key]['en'];
}
}
outputs:
modify-taxes
taxes-list
Just iterate over your array and find the translation:
$search = "liste-taxes";
$bouton["modify-customer"] = array("fr"=>"liste-client", "en"=>"customer-list");
$bouton["create-customer"] = array("fr"=>"creer-client", "en"=>"create-customer");
$bouton["modify-item"] = array("fr"=>"liste-item", "en"=>"item-list");
$bouton["create-item"] = array("fr"=>"creer-item", "en"=>"create-item");
$bouton["modify-taxes"] = array("fr"=>"liste-taxes", "en"=>"taxes-list");
$bouton["create-taxes"] = array("fr"=>"creer-taxes", "en"=>"create-taxes");
array_walk($bouton, function($v, $i) use($search) {
if($v['fr'] === $search) {
echo $v['en'];
}
});
array_walk($bouton, function ($val) use ($searched, $lang, &$result) {
if (in_array($searched, $val))
$result = $val[$lang];
});
where $searched is the string you search, $lang the language you search. $result will contain the final value.
Example:
$bouton["modify-customer"] = array("fr"=>"liste-client", "en"=>"customer-list");
$bouton["create-customer"] = array("fr"=>"creer-client", "en"=>"create-customer");
$bouton["modify-item"] = array("fr"=>"liste-item", "en"=>"item-list");
$bouton["create-item"] = array("fr"=>"creer-item", "en"=>"create-item");
$bouton["modify-taxes"] = array("fr"=>"liste-taxes", "en"=>"taxes-list");
$bouton["create-taxes"] = array("fr"=>"creer-taxes", "en"=>"create-taxes");
$searched = "liste-taxes";
$lang = "en";
array_walk($bouton, function ($val) use ($searched, $lang, &$result) {
if (in_array($searched, $val))
$result = $val[$lang];
});
print $result;
You could build a handy translate function....
function translate($array, $searchterm, $lan){
foreach($array as $key => $array){
if( in_array($searchterm,$array)){
return $array[$lan];
}}}
And then just pass it the array, the term, and the language,
and you'll get the fr, or en version depending on what you specify.
echo translate($bouton,"taxes-list","fr");
foreach($bouton as $key => $array){
if( in_array("taxes-list",$array)){
echo $key . PHP_EOL;
echo $bouton[$key]['en'];
}
}
Thaks to immulatin, phpisubuer01 and bwoebi !!! Work's like a charm.
I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later
I want to convert a big yaml file to PHP array source code. I can read in the yaml code and get back a PHP array, but with var_dump($array) I get pseudo code as output. I would like to print the array as valid php code, so I can copy paste it in my project and ditch the yaml.
You're looking for var_export.
You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.
Don't know why but I could not find satisfying code anywhere.
Quickly wrote this. Let me know if you find any errors.
function printCode($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= printCode($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
return $return;
}
return $data;
}
//REQUEST
$x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
echo printCode($x);
//OUTPUT
$array['key'] = 'value';
$array['key2']['key3'] = 'value2';
$array['key2']['key4'] = 'value3';
$array['key2']['key5'] = array();
Hope this helps someone.
An other way to display array as code with indentation.
Tested only with an array who contain string, integer and array.
function bo_print_nice_array($array){
echo '$array=';
bo_print_nice_array_content($array, 1);
echo ';';
}
function bo_print_nice_array_content($array, $deep=1){
$indent = '';
$indent_close = '';
echo "[";
for($i=0; $i<$deep; $i++){
$indent.=' ';
}
for($i=1; $i<$deep; $i++){
$indent_close.=' ';
}
foreach($array as $key=>$value){
echo "<br>".$indent;
echo '"'.$key.'" => ';
if(is_string($value)){
echo '"'.$value.'"';
}elseif(is_array($value)){
bo_print_nice_array_content($value, ($deep+1));
}else{
echo $value;
}
echo ',';
}
echo '<br>'.$indent_close.']';
}