removing "The " from array values to order alphabetically - php

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

Related

Where is the wrong in this foreach?

In the following structure:
$numbers = array("one", "two", "three", "four");
foreach ($numbers as $value) {
if( $value == 'two' ) {
echo '$value <br>';
}
else {
echo 'This numbers doesnt exist in the array';
}
}
I intend that if one of the if values is equal to two (in this case one of the values is equal to 2), I print the entire array, that is, one, two, three, and four, and for example, if I put that the if is equal to 5, since that value does not exist in the array, it is entered through the else. From the code I have provided, what have I done wrong?
The way your code works currently, you are iterating through each value in the array. If the value you are up to is the sentinel value (in this case the string "two") then you are printing it, otherwise you are printing another message.
If you wish to print the entire array if and only if it contains the sentinel value, you can use in_array() to check for the existence of the sentinel value first:
$sentinel = 'two';
if ( in_array($sentinel, $numbers ) ) {
foreach ( $numbers as $number ) {
echo "$number<br>";
}
} else {
echo "The number $sentinel does not exist in the array.";
}

PHP - How to find a between value from first array in second array

In two different arrays, I have to find between value of each array1 value.
$array1 = array(8,15,26);
$arrayBetween = array ("zero" => 0, "one"=>10,"two" =>20, "three" =>30);
Example: 8 is between zero and one.
I didn't find any function that can help me. I've tried with array_filter or range but I can't solve it.
You can write it yourself with a simple loop :
$array1 = array(-1,8,15,26,47);
$arrayBetween = array ("zero" => 0, "one"=>10,"two" =>20, "three" =>30);
foreach($array1 as $value)
{
// special cases if value is outside arrayBetween bounds
if($value < min($arrayBetween))
echo "$value is before " . array_keys($arrayBetween)[0] . PHP_EOL ;
elseif($value > max($arrayBetween))
{
$keys = array_keys($arrayBetween) ;
echo "$value if after " . end($keys) . PHP_EOL ;
}
else
{
$prevKey = null ; // store the previous key at each try
foreach($arrayBetween as $key => $nb)
{
if($nb > $value) // we found the first key that has value > current number
{
echo "$value is between $prevKey and $key ". PHP_EOL ;
break; // interval found, can stop the search
}
$prevKey = $key ; // save current key to display it if next element is > $value
}
}
}
Output :
-1 is before zero
8 is between zero and one
15 is between one and two
26 is between two and three
47 if after three

Retrieving values crossing arrays gives unlogic result

In Drupal context, while printing checked exposed filters in a somehow standard code snippet, I can't print more than one value, and I can't find the missing logic of my foreach loop :
<?php
foreach ($exposed_filters as $filter => $value) {
if ($filter == 'foo') {
$field = field_info_field('field_foo');
$allowed_values = list_allowed_values($field);
//returns an array with 14 string values & numeric keys
//e.g array(0=>'bla', 1=>'bar', 2=>'xx', 3=>'yy')
$h = explode(',', $value);//returns checked ids of foo filter e.g array(0 => 2, 1=>3)
$exp_heb = '';
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[$v] . ', ';
}
$exp_heb = substr($exp_heb, 0, -2);
print $exp_heb;
}
}
?>
Should return : xx, yy but I get xx,,
I checked step by step printing out my arrays, values... everything's looks fine but result is wrong. Do I need a rest ???
This is dpm($allowed_values) output
May be this line cuts your output?
$exp_heb = substr($exp_heb, 0, -2);
I got it working. I have to get the integer value of my variable, before passing it as a key :
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[intval($v)] . ', ';
}
For a reason I would be glad to be taught, even if it's always an id, and prints out a number, first time it's passed as integer, but then not.

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 [];

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

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/>";
}

Categories