Separating certain keys from an Array into two clearly distinct groups. How? - php

I would like to add stuff out of an array and translate them. However, some items in the array I do not want to translate and so encapsulate them into special tags. In this example i've uset < > but if you have suggestions/better iead's I'm open to them. I also thought of { } or [ ] and * * whichever you think is easiest.
<?php
# define the contents of my all time clients
$clients = array('<UNESCO>', 'Vrije Universiteit medical center');
# randomization engine
$keys = array_rand($clients, 3); // get 3 random keys from your array
foreach ($keys as $key) { // cycle through the keys to get the values
# if this item is inbetween < > tags..
if #??#######??########??#########??########??##
# then put this item directly into randomList without translation
$randomList .= "• " . $clients[$key]) . "<br/>"; // WORKS
# all other items without <tags> are first translated via __() then added
else $randomList .= "• " . __($clients[$key]) . "<br/>"; // WORKS
}?>
Question: What should be on line 10 to make the IF statement complete?
In other words, what is the logic in programming code that can match an item in the array being one of those special words that should not be translated and treaded differently?

Few possible solutions:
if (preg_match('~^<.*>$~', $clients[$key]))
if (strlen($clients[$key]) > 0 && $clients[$key][0] == '<' && substr($clients[$key], -1) == '>')

You probably want to ditch the brackets before outputting the name. You could use this then:
// note that you need to test against $clients[ $key ], not $key
if( preg_match( '~^<(.*)>$~', $clients[ $key ], $matches ) )
{
$randomList .= "• " . $matches[ 1 ] . "<br/>";
}

Related

php multi level foreach loop remove last comma from loop

hii i have 2 level foreach loop like this and i want to remove last comma from each loop ,
/* Here is the mysql query */
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "] , ";
}
output of this program :
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
],
And i want like this
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
]
i am already use implode , trim but is remove only one loop not remove second .
sol me my problem , thanks .
You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards.
However you don't want the comma for the first output.
$addComma = ''; // should be empty for the first lines.
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo $addComma."[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "]";
$addComma = " , "; // any lines following will finish off this output
}
Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information.
// Declare variable to hold the string of information.
$values = "";
/* Here is the mysql query */
foreach($loop1 as $val1)
{
$showvalone = $val1['data1'];
$values .= "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2)
{
$showvaltwo[] = $val2['data2'];
}
$values .= implode(",",$showvaltwo);
$values .= "] , ";
}
// Remove the last comma and spaces from the string.
$values = rtrim($values, ' , ');
// Output the information.
echo $values;
I have my own version in removing "," at the end and instead of adding a "."
$numbers = array(4,8,15,16,23,42);
/* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */
$last_key = end($ages);
// calling the arrays with "," for each array.
foreach ($ages as $key) :
if ($key === $last_key) {
continue; // here's the "," ends and last number deleted.
}
echo $key . ", ";
endforeach;
echo end($ages) . '.' ; // adding the "." on the last array

removing "The " from array values to order alphabetically

I have an array in which every value starts with a name of a venue. Some venues have a "The " in front of them which I want to remove so that when I sort() the array I don't end up with all the "The ..." venues at the "T".
I wrote this:
function remove_The($array) {
global $all_venue_listings;
// remove the "The" from the listings...
foreach($all_venue_listings as $v) {
if ( substr($v, 0, 4) === "The " || substr($v, 0, 4) === "the " || substr($v, 0, 4) === "THE " ) {
$v = preg_replace("/The /i","",$v);
}
}
return $all_venue_listings;
}
But that doesn't seem to put the changed values back into the array. How can I operate on the array in the foreach loop so that what I change goes back into the original array?
I tried replacing the preg_replace line with this:
$all_venue_listings[] = preg_replace("/The /i","",$v);
But that just creates a duplicate entry in the array (one with "The " and one without).
Two options.
1) Use a reference and update the element directly (note the &):
foreach($all_venue_listings as &$v) {
...
$v = ...
2) Use a key and update the original array:
foreach($all_venue_listings as $key => $v) {
...
$all_venue_listings[$key] = ...
Either will work. I prefer #1

Why won't PHP recognize two equal strings?

I'm working on a php function that will compare the components of two arrays. Each value in the arrays are only one english word long. No spaces. No characters.
Array #1: a list of the most commonly used words in the english
language. $common_words_array
Array #2: a user-generated sentence, converted to lowercase, stripped
of punctuation, and exploded() using the space (" ") as a delimiter.
$study_array
There's also a $com_study array, which is used in this case to keep
track of the order of commonly used words which get replaced in the
$study_array by a "_" character.
Using nested for loops, what SHOULD happen is that the script should compare each value in Array #2 to each value in Array #1. When it finds a match (aka. a commonly used english word), it will do some other magic that's irrelevant to the current problem.
As of right now, PHP doesn't recognize when two array string values are equivalent. I'm adding in the code to the problematic function here for reference. I've added in a lot of unnecessary echo commands in order to localize the problem to the if statement.
Can anybody see something that I've missed? The same algorithm worked perfectly in Python.
function create_question($study_array, $com_study, $common_words_array)
{
for ($study=0; $study<count($study_array); $study++)
{
echo count($study_array)." total in study_array<br>";
echo "study is ".$study."<br>";
for ($common=0; $common<count($common_words_array); $common++)
{
echo count($common_words_array)." total in common_words_array<br>";
echo "common is ".$common."<br>";
echo "-----<br>";
echo $study_array[$study]." is the study list word<br>";
echo $common_words_array[$common]." is the common word<br>";
echo "-----<br>";
// The issue happens right here.
if ($study_array[$study] == $common_words_array[$common])
{
array_push($com_study, $study_array[$study]);
$study_array[$study] = "_";
print_r($com_study);
print_r($study_array);
}
}
}
$create_question_return_array = array();
$create_question_return_array[0] = $study_array;
$create_question_return_array[1] = $com_study;
return $create_question_return_array;
}
EDIT: At the suggestion of you amazing coders, I've updated the if statement to be much more simple for purposes of debugging. See below. Still having the same issue of not activating the if statement.
if (strcmp($study_array[$study],$common_words_array[$common])==0)
{
echo "match found";
//array_push($com_study, $study_array[$study]);
//$study_array[$study] = "_";
//print_r($com_study);
//print_r($study_array);
}
EDIT: At bansi's request, here's the main interface snippet where I'm calling the function.
$testarray = array();
$string = "This is a string";
$testarray = create_study_string_array($string);
$testarray = create_question($testarray, $matching, $common_words_array);
As for the result, I'm just getting a blank screen. I would expect to have the simplified echo statement output "match found" to the screen, but that's not happening.
(EDIT) make sure your that your splitting function removes excess whitespace (e.g. preg_split("\\s+", $input)) and that the input is normalized properly (lowercase'd, special chars stripped out, etc.).
On mobile and can't seem to copy text. You forgot a dollar sign when accessing the study array in your push command.
change
array_push($com_study, $study_array[study]);
to
array_push($com_study, $study_array[$study]);
// You missed a $ ^ here
Edit:
The following code outputs 3 'match found'. i don't know the values of $common_words_array and $matching, so i used some arbitrary values, also instead of using function create_study_string_array i just used explode. still confused, can't figure out what exactly you are trying to achieve.
<?php
$testarray = array ();
$string = "this is a string";
$testarray = explode ( ' ', $string );
$common_words_array = array (
'is',
'a',
'this'
);
$matching = array (
'a',
'and',
'this'
);
$testarray = create_question ( $testarray, $matching, $common_words_array );
function create_question($study_array, $com_study, $common_words_array) {
echo count ( $study_array ) . " total in study_array<br>";
echo count ( $common_words_array ) . " total in common_words_array<br>";
for($study = 0; $study < count ( $study_array ); $study ++) {
// echo "study is " . $study . "<br>";
for($common = 0; $common < count ( $common_words_array ); $common ++) {
// The issue happens right here.
if (strcmp ( $study_array [$study], $common_words_array [$common] ) == 0) {
echo "match found";
}
}
}
$create_question_return_array = array ();
$create_question_return_array [0] = $study_array;
$create_question_return_array [1] = $com_study;
return $create_question_return_array;
}
?>
Output:
4 total in study_array
3 total in common_words_array
match foundmatch foundmatch found
Use === instead of ==
if ($study_array[$study] === $common_words_array[$common])
OR even better use strcmp
if (strcmp($study_array[$study],$common_words_array[$common])==0)
Use built-in functions wherever possible to avoid unnecessary code and typos. Also, providing sample inputs would be helpful too.
$study_array = array("a", "cat", "sat", "on","the","mat");
$common_words_array = array('the','a');
$matching_words = array();
foreach($study_array as $study_word_index=>$study_word){
if(in_array($study_word, $common_words_array)){
$matching_words[] = $study_word;
$study_array[$study_word_index] = "_";
//do something with matching words
}
}
print_r($study_array);
print_r($matching_words);

Php array in a foreach loop

I have been trying to create a Multidimensional array from an already existing array. The reason I am doing this is so I can separate the super array into a more categorized version so that later on I can run foreach on just those categories in another script.
This is a snippet of code // Please read comments :)
$and = array();
if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
{
foreach($this-> input-> post('and') as $value) // if reason_ is present
{
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
{
foreach($this-> input-> post('and') as $value) // If it is in the super array
{
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
This approach is not giving me expected outcome however, I am getting a big string like so :
array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
So to my knowledge (which is limited) when I try to do a foreach over the array
[reason_and]
I only get one loop since the array ["reason_and] only has one value (the 24 character string?). Is it possible to have the reason_and have a value for each of the numbers?
Is this even possible? I'm quite confused.
I've referred to this question for reference but I still do not get a outcome that I can work with. Thanks in advance.
This
$and['reason_and'] .= end(explode('_', $value)) . ' , ';
^^^^----
should be
$and['reason_and'][] = end(explode('_', $value)) . ' , ';
^^--
which turns it into an "array push" operation, not a string concatenation. Then 'reason_and' will be an array, and you foreach over it.
first of all preg_grep returns an array with matched values, so
$andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field
if($andArray) {
$reason = preg_grep("/reason_/", $andArray); // Search for the reason_
if($reason) { // if reason_ is present
foreach($reason as $value) {
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
$status = preg_grep("/status_/", $andArray); // Search for status
if($status) {
foreach($status as $value){ // If it is in the super array
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
Or if you need result as array, then remove ' , ' and replace dot with [];

PHP elseif statement not executed even though initial if statement is false

I am writing a recursive function to print out the differences between 2 multildimensional php arrays. The purpose of this code is to see the difference between jpeg headers to deteremine how adobe bridge cs3 is saving rating information within the jpg file.
When I am single-stepping through the code using my eclipse - zend debugger ide, it appears that even though the initial if statement is false (ie neither values is an array), the subsequent elseif statements are never executed. The function is attached below.
Note: Changes since original post based on comments
Added a default level= ''
Removed comments between the if{} elseif{} blocks
Removed an else; at the end of the block that had no function
Encoded the < and > symbols so angle bracket would show in my code
function array_diff_multi($array1,$array2,$level=''){
$keys = array_keys($array1);
foreach($keys as $key)
{
$value1 = $array1[$key];
if(array_key_exists($key,$array2) ){
$value2 = $array2[$key];
if (is_array($value1) && is_array($value2)){ // Check if they are both arrays, if so recursion is needed
array_diff_multi($value1,$value2,$level . "[ " . $key . " ]");
}
elseif(is_array($value1) != is_array($value2)){ // Recursion is not needed, check if comparing an array to another type
print "<br>" . $level . $key ."=>" . $value1 . "as array, compared to ". $value2 ."<br>";
}
elseif($value1 != $value2){ // the values don't match, print difference
print "<br>" . $level . $key ."=>" . $value1 ." != " . $value2 ."<br>";
}
}
else{
print "<br>" . $level. $key . "does not exist in array2";
}
}
}
could it be because you have
else;
at the end...?
Try removing that or turning that into 'real code'
It works fine for me here. I put your function (with the tiny difference of adding a default value of '' to the level parameter), and these two arrays:
$a1 = array('foo', 'bar', 2, array('baz', '3', 4, array(54,45)));
$a2 = array('faz', 'bar', 4, array('buz', '3', 5, 54));
And got this output:
0=>foo != faz
2=>2 != 4
[ 3 ]0=>baz != buz
[ 3 ]2=>4 != 5
[ 3 ]3=>Arrayas array, compared to 54
Perhaps your starting arrays are not what you think they are...?
This doesn't exactly answer your question, but I think Adobe Bridge saves metadata in dotfiles in the same directory as the files. For example, sort information is saved in a .bridgesort file.
The only way that all the elseifs would be skipped is if the two variables are not arrays and are equal.

Categories