For Loop Display Fact - php

I'm trying to figure out why I am getting a undefined offset of 1 for this for loop I'm writting. I have an array ($facts) that has specific key values pairs and I'm trying to see if on each iteration the $i matches one of the keys in the array. If the key isset and in the array I need to display the value of that key.
for ($i = 1; $i <= 100; $i++) {
if (isset($i) && in_array($i, $facts[$i])) {
echo $facts[$i];
}
echo $i;
}
UPDATE: Use the function isset to test if the incremented value equals one of the keys in the $facts array. If there is a key that matches, display the value after the number.

I think this is the correct way of checking (removing the in_array()).
for ($i = 1; $i <= 100; $i++) {
echo $i; // Now the number is first.
if (isset($facts[$i])) {
// This is only echoed if $i exists as a key.
echo $facts[$i];
}
}
If you only want to show the number if the fact exists, move echo $i inside the if-statement (or better yet, use foreach($facts as $key => $value) in that case).

You could check $facts[$i]
for ($i = 1; $i <= 100; $i++) {
if (isset($facts[$i]) && in_array($i, $facts[$i])) {
echo $facts[$i];
}
echo $i;
}

Related

Warning: in_array() expects parameter 2 to be array, null given (loop)

I'm looping for string overlaps between two arrays, deleting those values where there is one, so that only the empty values of $check remain, in this case $check[5].
The second one, $check, is multidimensional.
$names = ["bob", "selena", "hailey", "rob", "justin", "robocop"];
$check = [
["justin"], //bob
["justin", "selena", "robocop"], //selena
["justin"], //hailey
["justin", "rob"], //rob
[], //justin
["justin", "selena", "bob"] //robocop
];
for ($i = 0; $i < count($names); $i++) {
for ($j = 0; $j < count($check); $j++) {
if (in_array($names[$i], $check[$j])) {
unset($check[$j]);
}
}
}
The first loop runs through $names, the second through $check.
If the current string from $names ($names[i])
is present in the current array of $check ($check[j])
the array is removed.
However, the console prints a warning: in_array() expects parameter 2 to be array, null given. I find this strange, because $check[j] should be equal to one of the arrays inside of $check.
Is there any way I can fix this?
After a few iterations of the outer loop, you will have unset most of $check. With a for loop like that, you're counting on specific numeric keys being there, but since you unset them, their values are undefined, a.k.a. null.
You can avoid this by using foreach loops instead.
foreach ($names as $name) {
foreach ($check as $key => $array) {
if (in_array($name, $array)) {
unset($check[$key]);
}
}
}
As you are keep on unsetting the $check array, the size of the $check array will go down. Hence the $check won't return a value for the higher values of $j
You can do a minor modification in this code segment as follows
$checkcount = count($check);
for ($i = 0; $i < count($names); $i++) {
for ($j = 0; $j < $checkcount; $j++) {
if (isset($check[$j]) && in_array($names[$i], $check[$j])) {
unset($check[$j]);
}
}

remove duplicate arrays in loop

I have an associative array that might contain duplicates. I am trying to loop through the array and compare the current element with the next element in the array. If there is a duplicate, it should be removed.
The code below removes one instance of the element. In the test array I'm using, I have 3 duplicate part numbers, but my code only removes one. I'm left with two. I only want one to remain.
$length = count($items);
for($i = 0; $i < $length -1; $i++){
if($items[$i]['part_number'] == $items[$i+1]['part_number']){
unset($items[$i+1]);
$items = array_values($items);
}
}
What am I doing wrong here?
You need to loop backwards through the array, and delete the current item.
$length = count($items);
for($i = $length - 1; $i > 0; $i--){
if($items[$i]['part_number'] == $items[$i-1]['part_number']){
unset($items[$i]);
}
}
becuase your code is
The $ items value is in the for statement.
if you want unique array, you have to array_unique function
http://php.net/manual/en/function.array-unique.php
In your case after you unset element, $i++ in for loop, you reindexed your array and you skip one element. Add $i-- if you unset item. Or you can reindex your array after for loop.
This is also a very simple example you can start improving with.
<?php
$test = ['sample', 'sample', 'sample', 'not', 'not', 'no', 'no'];
$test2 = [];
$k = 0;
foreach ($test as $key => $value) {
if ($key == 0) {
$test2[$k] = $value;
$k++;
} else {
if ($test2[$k - 1] != $value) {
$test2[$k] = $value;
$k++;
}
}
}
$test = $test2;
var_dump($test);
One dirty hack is to check again if you have a duplicate by decreasing $i.
for($i = 0; $i < $length -1; $i++){
if($items[$i]['part_number'] == $items[$i+1]['part_number']){
unset($items[$i+1]);
$items = array_values($items);
$i--;
}
}
This way it will again test your previous value against next item in array.
So if 0==1, then next time if 0==2.
Your code did 0==1 then (2)==(3).

Object iteration using for loop

Object iteration with foreach is easy:
foreach ($item->attributes as $attribute) {
// echo $attribute->name;
}
.. but I wonder if its possible to do the same with for instead:
for ($j=0; $j < count($item->attributes); $j++) {
// echo $item->attributes->$j->$name ?
}
Although I can create a counter outside foreach and increment it, but just wanted to know if for works for objects.
For reference, the object(s) I'm working with looks like this.
for loops works for arrays which have incremented or decremented numeric index, and for associative arrays you have to use foreach unless you have separate arrays of keys, for example:
$count = count($keys);
for($i=0; $i < $count; $i++) {
echo $arr[$keys[$i]];
}
or you can reindex your assocative arrays, using array_values
$arr = array_values($assoc_array);
$count = count($arr);
for($i=0; $i < $count; $i++) {
echo $arr[$i];
}
for objects, they are properties, which can't be start from numbers, therefore you have to convert your object to array and reindex keys.
$arr = array_values(json_decode(json_encode($object), true));
$count = count($arr);
for($i=0; $i < $count; $i++) {
echo $arr[$i];
}
try to avoid above and use foreach instead.
for ($j=0; $j < count((array)$item->attributes); $j++) {
echo $item->attributes[$j];
}
Is this what you mean? You directly access this object that way, same as above, and you cast it beforehand to count.

Making associative array

My goal is to make ant assoc array from the values of for loop.
//$from_time value is 6 and $to_time value is 23
for ($i = $from_time; $i <= $to_time; $i++) {
$working_time_array[] = $i;
}
echo json_encode($working_time_array);
The output I get on AJAX success, and when I console.log it, I get result as such :
["6",7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
Preferred result is
["6","7","8","9","10"]... etc
The only difference between the two results is one result set contains integers and the other contains strings. If you want those values to be strings just cast them when assigning them to the array:
for ($i = $from_time; $i <= $to_time; $i++) {
$working_time_array[] = (string) $i;
}
This really shouldn't be necessary unless your client side is expecting strings only.
You would need to cast $i to a string before pushing it to the array.
for ($i = $from_time; $i <= $to_time; $i++) {
$working_time_array[] = (string)$i;
}
why would you convert int to string?
for your goal this should work
for ($i = $from_time; $i <= $to_time; $i++) {
$working_time_array[] = "$i";
}
echo json_encode($working_time_array);

Return values of an array from behind (last element) php

say I have an array
$test_backwards=array("something1","something2","something3");
this is just a testing example and it's important to note that values will be added dinamically in my final array. so is it possible to dynamically return values from behind, namely starting from the last element?
something like this but backwards
for($i=0;$i<count($test_backwards);$i++) {
echo $test_backwards.'<br>';
}
Just start at the end and decrement your index:
for ($i = count($test_backwards) - 1; $i >= 0; $i--) {
echo $test_backwards[$i].'<br>';
}
or use array_reverse() (slower):
$test_backwards = array_reverse($test_backwards);
for ($i = 0; $i < count($test_backwards); $i++) {
echo $test_backwards[$i].'<br>';
}
You can also use array_pop(), if you do not need to keep this array. Or you can assign it to a temp array and then array_pop it, it will get and delete value from last.
$temp = $test_backwards;
while(($item = array_pop($temp)) !== NULL ) {
echo $item;
}

Categories