I compare a string from a feed with another variable and echo a corresponding string.
$xml = #simplexml_load_file($feed);
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
}
if (($caller == $id) {
echo '$message';
}
I want to echo no more than 5 messages, regardless of the number of ($caller == $id) matches.
$x=1;
while (($caller == $id) && ($x<=5)) {
echo '$x $message';
$x++;
}
That general approach has failed.
I thought maybe I could put the condition in a function and call it a certain number of times but no luck.
function myFunction(){
echo '$message';
}
$x=1;
while($x<=5) {
echo '$x';
myFunction();
$x++;
}
For one, your while loop would actually only output 4 results because you are saying while x is LESS than 5, not <= 5. You can leave it < 5, but change x to equal 0 instead of 1;
The second problem is that as soon as $caller does not == $id, your while loop will stop. You should only need to use a foreach loop for this, not both a foreach to extract the data and a while to loop over it again.
The third problem with your code is that you are writing your caller and message values to the same variable over and over in your foreach. Then, in your while loop, your $caller and $message variables will always be equal to the last items in the $xml->entry array.
$xml = #simplexml_load_file($feed);
$number_of_results_to_show = 5;
$x = 0; // counter
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
if ($caller == $id && $x < $number_of_results_to_show) {
$x++;
echo $message;
}
// also, you can use a break to prevent your loop from continuing
// even though you've already output 5 results
if ($x == $number_of_results_to_show) {
break;
}
}
I assume that you have an array $xml->entry and you want to print message[0] of up to 5 array elements. Message is printed if $caller matches $id.
$xml = #simplexml_load_file($feed);
// Iterate through $xml->entry until the end or until 5 printed messages
for($i = 0, $j = 0; ($i < count($xml->entry)) && ($j < 5); ++$i) {
$caller = $xml->entry[$i]->caller[0];
$message = $xml->entry[$i]->message[0];
if ($caller == $id) {
echo "$message";
++$j;
}
}
If you want to store results from $xml->entry then:
$xml = #simplexml_load_file($feed);
$storedResults = new array();
foreach($xml->entry as $entry) {
$caller = entry->caller[0];
$message = entry->message[0];
// Store data in array. $storedResults will be an array of arrays
array_push(storedResults, array( 'caller' => $caller, 'message' => $message ));
}
// Print up to 5 messages from the stored results
$i = 0, $j = 0;
while (($i < count($storedResults)) && ($j < 5)) {
if ($storedResults[$i]['caller'] == $id) {
echo $storedResults[$i]['message'];
++$j;
}
++$i;
}
Related
//declare array variable
$data['direct_sponsor_bonus_vals']=array('package_size'=>'');
// insert element to array
for ($x = 0; $x <= 10; $x++) {
$data['direct_sponsor_bonus_vals']=array('package_size'=>$x);
}
//show output
foreach($direct_sponsor_bonus_vals As $key => $value )
{
echo $value . ",";
}
Output :
10,
How to make Output become like below :
0,2,3,4,5,6,7,8,9,10
I have tried replace
$data['direct_sponsor_bonus_vals']=array('package_size'=>$x);
by
$data['direct_sponsor_bonus_vals']['package_size'][] = $x;
but still not working.
Update :
I think the bug is at foreach loop. Need 2 of foreach loop. I tried:
foreach ($direct_sponsor_bonus_vals As $key => $value )
{
foreach ($value As $key_inner => $value_inner)
{
echo $value_inner; // whatever
}
}
Still has bug error : Invalid argument supplied for foreach()
I didn't actually understand which part of your code meant for a view but I think this is what you are looking for
In a Controller
$array = null;
for ($x = 0; $x <= 10; $x++) {
$array[]= array('package_size'=>$x);
}
//to send above array to view just do $data['direct_sponsor_bonus_vals'] = $array;
in a view
foreach($direct_sponsor_bonus_vals as $value)
{
echo $value['package_size'] . ",";
}
I have to push an associative array in a normal array (not to convert).
Example (NO CODE):
project = {}
element["title"] = "My title"
element["description"] = "My description"
is there a way to have this
echo $project->title;
//or
echo $project[0]["title"]
?
I'v tried this, but server says: ERROR 500
$i = 0;
$projects = {};
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}
$projects = {}; is not valid php.
If you want to initialize an empty array (associative or numeric, that does not matter), you need:
$projects = [];
or on older php versions:
$projects = array();
Also note that you need to do the same to your $elements array at the beginning of each iteration otherwise it will grow on every iteration. Assuming that the descriptions are not all the same...
foreach($projectsElements as $element) {
$elements = [];
while($i <= $nRowsForProject) {
...
And your while loop does not seem to make a lot of sense: You are not using the $i variable in your loop so are just doing the same assignments on each iteration.
$projects = []; // declare empty array
foreach($projectsElements as $element) {
$projects []= $element; // push $element into $projects array
}
$i = 0;
$projects = array();
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$elements = array();
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}
My code is below.
1) I needed to get the number of words in each message in the message array and display it in a new array
2) If the number of words in each message was less than 5 I am supposed to add the words "smaller" to another new array and if the number of words in each message is greater than 5 I an supposed to add the string"bigger" to this same new array.
I am unsure of how to put this "bigger" and "smaller" into a new array. Please advise.(refer question 2)
$messages = array(
"Learning PHP is fun",
"I want to learn more",
"Girls can code too",
"Goodbye boredom!",
"Coding Geek",
"Computers can sometimes freeze up",
"Follow me now", "Coding is cool",
"Computer nerds are for real",
"This is the end of all the messages"
);
/* (1) */
for ($i = 0; $i < 10; $i++) {
$words[] = str_word_count($messages[$i]);
}
print_r($words);
echo "<br>";
/* (2) */
for ($i = 0; $i < 10; $i++) {
if ($words[$i] <= 5) {
$size[] = $words[$i];
echo "smaller" . "<br>";
} else {
$size[] = $words[$i];
echo"bigger";
}
}
First, you can use foreach instead of for loop in this case.
Second, this code is enough.Try it :
foreach($messages as $val){
$len = str_word_count($val);
if($len<=5){
$msg = "bigger";
}else{
$msg = "smaller";
}
$size[] = array("size"=>$len, "msg"=>$msg);
}
# Your $size array would be like :
# array(
# array("size"=>3, "msg"=>"smaller"),
# array("size"=>8, "msg"=>"bigger")
# )
# And you can print it or use it everywhere.
for loops work fine for arrays. You could think about using a variable which holds the length of the original array to use in the loop.
$numberOfMessages = count($messages);
$for ($i = 0; $i < $numberOfMessages; $i ++) {
...
}
My preferred way of doing this is the same as the first two examples using a foreach loop.
foreach ($messages as $message) {
$words[] = str_word_count($message);
}
This will create your first new array called $words by counting the number of words in each value ($message) from the original array ($messages). Using the <pre> tag formats the echo and makes it more readable.
echo '<pre>' . print_r($words, true) . '</pre>';
Your second new array is made is a similar way.
foreach ($words as $word) {
if ($word < 5) {
$size[] = 'smaller';
} else {
$size[] = 'bigger';
}
}
This time we take each value ($word) from our new $words array and check to see what size it is and populate the second new array $size. bablu's example using the ternary operator ?: This example is just the long-hand way of writing the same conditional statement.
Putting it all together
$messages = array (
'Learning PHP is fun',
'I want to learn more',
'Girls can code too',
'Goodbye boredom!',
'Coding Geek',
'Computers can sometimes freeze up',
'Follow me now', 'Coding is cool',
'Computer nerds are for real',
'This is the end of all the messages'
);
foreach ($messages as $message) {
$words[] = str_word_count($message);
}
echo '<pre>' . print_r($words, true) . '</pre>';
foreach ($words as $word) {
if ($word < 5) {
$size[] = 'smaller';
} else {
$size[] = 'bigger';
}
}
echo '<pre>' . print_r($size, true) . '</pre>';
Try this: its working fine for me:
<?php
$messages=array
("Learning PHP is fun","I want to learn more","Girls can code too","Goodbye boredom!","Coding Geek","Computers can sometimes freeze up","Follow me now","Coding is cool","Computer nerds are for real","This is the end of all the messages");
$newMessageArray = array();
$newCountArray = array();
foreach($messages as $message) {
$length = str_word_count($message);
$newMessageArray[] = $message;
$newCountArray[] = ($length >=5)?'Bigger':'Smaller';
}
echo '<pre>'; print_r($newMessageArray);
echo '<pre>'; print_r($newCountArray);
?>
I have an array:
$arr=array("A","B","C");
I want to make its all of combination as:
array("A")
array("B")
array("C")
array("A","B")
array("A","C")
array("B","C")
array("A","B","C")
i want to make an process all of this combinations but i don't want generate all combinations, store them in an array and apply function to them. Because this requires a lot of memory with large combinations. I have 40 items for this process (I have long time but i don't have enough memory).
I want to have a function like this:
function ProcessArrayCombinations($array){
foreach($array as $v){
//generate and process next combination of array
print_r($nextcombination);
}
}
Thank you.
This code recognizes the combinations as binary numbers, using the fact that there is a formula which states that the sum of all combinations possible from n elements is 2^n. Knowing its binary logarithm is integer, we can define a model where each possible binary number constructed from n digits is a set of combinations. Code is untested, if there are typos, please, let me know in comments.
function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}
$elementCount = count($status);
$trues = 0;
while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
//for ($i = 0; $i < count($status); $i++) {
// if ($status[$i}) {
// print
// } else {
// don't print
// }
//}
}
}
I edited and used your function as below. Thank you again Lajos.
function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}
$elementCount = count($status);
$trues = 0;
while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
for ($i = 0; $i < count($status); $i++) {
if ($status[$i]) {
echo $array[$i];
}
}
echo '<br/>';
}
}
I have an issue to deal with here (a logical error in my code 99%). I just can't seem to find the way to fix it, but I bet one of you will find the problem in no time!
I have to create a function which sorts array passed to it in asc or desc order, but can't use any array sorting functions !
I've been struggling with loops until now and I finally want to ask help from other devs ( you ).
Currently only code for ascending is worked on, descending will be no problem I assume once I do this one. It kinda of does sort values up to some point, but then stops ( it stops if the next smallest value is at the end of the passed array ). What could I do to prevent this and make it sort the whole array and it's elements?
Here is the code so far.
<?php
function order_array($array,$mode = 'ascending') {
$length = count($array);
if($mode == 'descending') {
return $array;
} else {
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
}
return $sorted_array;
}
}
$array_to_sort = array(1, 3, 100, 99, 33, 20);
$sorted_array = order_array($array_to_sort);
print_r($sorted_array);
?>
I've solved the issue myself by doing it completely different. Now it sorts correctly all the elements of the passed in array. The logical issue I had was of using for() loop. The for() loop ran only a set ( length of passed array ) number of times, while we need it to loop more than that, because we will need to loop all the way untill we have a new sorted array in ascending order. Here is the code that will work
function order_array($array,$mode = 'ascending') {
if($mode == 'descending') {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MAX($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
} else {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MIN($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
}
}
function order_array($array,$mode = 'ascending') {
$length = count($array);
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
if($mode == 'descending') {
return array_reverse($sorted_array);
}
return $sorted_array;
}
}