I want to echo one element of the array like sum1. But I only get one letter like s. Please solve this problem.
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value[0];
echo $value[1];
}
If you want to just echo 1 item from that array, you should to it like this:
echo $nums[0];
If you want to loop through all of them, and show each, do it like so:
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value."<br>";
}
What you did wrong
You had already looped through the array, so you had a string. You can select the first letter from a string like in this example:
$string = "A string";
echo $string[0];
Will return A, as it's the first index of that string. That is essentially what you did in your loop.
You made your String an array, and it showed the index's you selected to be shown. You can read this where the questions asks how to do this. I hope this gives some more clearity.
If you want every element of array,
then,
For your array,
$nums = array("sum1", 100, 200);
$nums[0] will be sum1
$nums[1] will be 100
$nums[2] will be 200,
Now your loop,
foreach ($nums as $value) {
// here echo $value values are like 'sum1', 100, 200 will be printed.
// by default string will be considered as array,
// if you print $value[0], $value[1], $value[2], $value[3] for sum1, it will return, s, u, m, 1 respectively.
// and integers will be considered as pure value, which you will get in $value only, not in $value[0], ....
}
I hope I explained your concern.
Thanks.
Related
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.";
}
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.
This code picks 2-6 pitches from the $vec array. I'd like to echo out each individual pitch, but interestingly enough, it gives me the numeric values of the placement of the pitch in the array (ie: 2 5 6 instead of D F F#)
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec,$pick);
foreach ($random_keys as $pitch){
echo $pitch; echo "<br>";
}
Why is it doing this and how can I get the pitches instead of the numbers?
Try this:
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec, $pick);
foreach ($random_keys as $key) {
echo $vec[$key], '<br />';
}
From array_rand() documentation:
Return value
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16
How do you echo only the first line of print print_r?
More info:
I have this PHP code:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
print print_r($value, 1).'<br>';
}
That results in:
12567682
12764252
12493678
14739908
(or other numbers depending on user input)
I tried:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
$id = print_r($value, 1).'<br>';
}
echo $id
But it results in 1 random number from the list. In other words, the result only shows when using print like ' print print_r($value, 1).'<br>';'. The problem is that I only want the first, inorder, result to be shown. As if:
$firstlineofnumbers = '12567682';
echo $firstlineofnumbers;
Hope this makes sense. Thanks (:
If I understood what you're trying to do, just adding a break; statement after outputting the first value should be enough:
foreach(end($matches) as $key=> $value){
print print_r($value, true).'<br>'; // print_r() expects true, not 1
break;
}
If the keys in $matches are always numeric keys, this code should be enough:
echo $matches[0];
Otherwise, try this code:
$keys = array_keys($matches);
echo $matches[array_shift($keys)];
$keys will contain all keys of $matches.
array_shift will return the first value of $keys (the first key).
So the last line will display the corresponding value.
There is no need to loop through the entire array if you only need to display the first element.
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
$i=0;
foreach(end($matches) as $key=> $value){
$i++;
if ($i == 1) {
echo $value."<br />";
}
}
This starts with the variable $i which increases by 1 for each match. If $i == 1, then it will echo the $value.