Issues with in_array - php

I have the following fairly simple code, where I need to determine if a certain value exists in an array:
$testvalue = $_GET['testvalue']; // 4
$list = '3, 4, 5';
$array = array($list);
if (in_array($testvalue, $array)) { // Code if found } else { // Code if not found }
Even though it is obvious that the number 4 is in the array, the code returns the code inside the else bracets. What have I done wrong?

Change the third line:
$array = array_map('trim', explode(',',$list));

$array here is:
$array = array('3, 4, 5');
which is not the same as:
$array = array(3, 4, 5);
So, fix the way you are creating this array.. don't do it from a string.

Your array contains just one value, the string 3, 4, 5.
See the example on CodePad.
If you want to convert your string in an array, you can use:
$array = explode(', ', $list);
I have added a space behind the comma, but a safer method would be to use just a comma and then trim all values.

Related

laravel 5.4 variable parameter in query, giving wrong result?

$ids = '1, 2, 3';
$data = Modelname::whereNotIn('id', [$ids])->take(1)->get();
Above query giving wrong result. but following query giving right result.
$data = Modelname::whereNotIn('id', [1, 2, 3])->take(1)->get();
So, how to pass the variable parameter in query(laravel 5.4).
Use as below to make array
$ids = '1, 2, 3';
$idArr = explode(", ",$ids);
$data = Modelname::whereNotIn('id', $idArr)->take(1)->get();
Take care of space among ids $ids = '1, 2, 3'; and exploding by string
The whereNotIn accepts an array as its second argument.
So if you have a comma separated string which you do in your first scenario you need to explode it into an array, and then pass it to whereNotIn.
$ids = '1,2,3';
$idsArray = explode(',', $ids); // produces [1, 2, 3]
// it's always a good idea to add a check because if array is empty then an SQL exception will be thrown.
if(count($idsArray) > 0) {
$data = Modelname::whereNotIn('id', $idsArray)->take(1)->get();
}
Hope this helps.

Remove all elements before x from an array php

if I give you:
$array = array(object1, object2, object3, object4);
and say, at position 2, remove all elements before this position so the end result is:
$array = array(object3, object4);
What would I do? I was looking at array_shift and array_splice to achieve what I wanted - how ever I am not sure which to use or how to use them to achieve the desired affect.
Use array_slice. For more detail check link http://php.net/manual/en/function.array-slice.php
$array = array(object1, object2, object3, object4);
$array = array_slice($array,2); // 2 is position
Or if you are looking into the values instead of the index, with a tiny adjustment in #Ashwani's answer you can have:
$array = array('object1', 'object2', 'object3', 'object4');
$slice = array_slice($array, array_search('object3',$array));
array_slice is one way to go about it, however, if you are wanting to remove all the elements in an any array before a specific value, without searching, then:
//assuming you've already verified the match is in the array
//make a copy of $array first if you don't want to break the original
while($array[0] !== $match) {
array_shift(&$array);
}
Alternatively, you could:
$index = array_search($match, array_values($array));
if($index !== false) $array = array_slice($array, $index);
This accomplished both the verification and slice. Note the array_values() is used to account for associative arrays.

PHP - counting an imploded array

I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2
My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);
implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);
Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.

How to push additional fields into an Array in Php ?

Hello I'm looking to find the best practice to push an additional field into an Array with php.
I've tried both array_push and its equivalent $array[] = $var; but its not what I'm looking to get.
I have a loop like so:
foreach($lakesNearby as $lakes){
$dist = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
$lakes['distance'] = $dist;
$lakesReturned[] = $lakes;
}
But I'm sure there is a better way to combine the two last lines and push it into $lakesNearby ?
Hmmm..., maybe that:
foreach($lakesNearby as &$lakes){
$lakes['distance'] = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
}
all data will be in $lakesNearby array, you don't need another array.
As Alex said in the comment:
Just for completeness, see php.net/manual/de/control-structures.foreach.php : "In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Populating PHP list() with values in an array

I have an array:
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
I want to have the elements in that array appear as the variables in my list():
list($foo, $bar, $bash, $monkey, $badger) = $data;
Without actually specifying the variables, I tried;
list(implode(",$", $arr)) = $data; and
list(extract($arr)) = $data;
But they don't work, I get:
Fatal error: Can't use function return value in write context
Does anyone have any idea whether this is possible?
UPDATE: more context:
I am getting a CSV of data from an API, the first row is column names, each subsequent row is data. I want to build an associative array that looks like this:
$data[0]['colname1'] = 'col1data';
$data[0]['colname2'] = 'col2data';
$data[0]['colname3'] = 'col3data';
$data[1]['colname1'] = 'col1data';
$data[1]['colname2'] = 'col2data';
$data[1]['colname3'] = 'col3data';
Before I do that, however, I want to make sure I have all the columns I need. So, I build an array with the column names I require, run some checks to ensure the CSV does contain all the columns I need. Once thats done, the code looks somewhat like this (which is executed on a foreach() for each row of data in the CSV):
//$data is an array of data WITHOUT string indexes
list( $col1,
$col2,
$col3,
...
$col14
) = $data;
foreach($colNames AS $name)
{
$newData[$i][$name] = $$name;
}
// Increemnt
$i++;
As I already HAVE an array of column name, I though it would save some time to use THAT in the list function, instead of explicitly putting in each variable name.
The data is cleaned and sanitised elsewhere.
Cheers,
Mike
I want to have the elements in that array appear as the variables in my list():
i think there is your problem in understanding. list() does not create a new list structure or variable, it can only be used to assign many variables at once:
$arr = array(1, 2, 3);
list($first, $second, $third) = $arr;
// $first = 1, $second = 2, $third = 3
see http://php.net/list for more information.
you are probably looking for an associative array. you can create it with the following code:
$arr = array('first' => 1, 'second' => 2, 'third' => 3);
// $arr['first'] = 1, …
If some rows in your input file are missing columns, you can't really know which one is missing. Counting the number of values and aborting or jumping to next row when less than expected should be enough.
... unless you set the rule that last columns are optional. I'll elaborate on this.
Your code sample is far for complete but it seems that your problem is that you are using arrays everywhere except when matching column names to cell values. Use arrays as well: you don't need individual variables and they only make it harder. This is one of the possible approaches, not necessarily the best one but (I hope) clear enough:
<?php
$required_columns = array('name', 'age', 'height');
$input_data = array(
array('John', 33, 169),
array('Bill', 40, 180),
array('Ashley', 21, 155),
array('Vincent', 13), // Incomplete record
array('Michael', 55, 182),
);
$output = array();
foreach($input_data as $row_index => $row){
foreach($required_columns as $col_index => $column_name){
if( isset($row[$col_index]) ){
$output[$row_index][$column_name] = $row[$col_index];
}
}
}
print_r($output);
?>
I've used $row_index and $col_index for simplicity.
Original answer, for historical purposes only ;-)
I can't really understand your specs but PHP features variable variables:
<?php
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
foreach($arr as $i){
$$i = $i;
}
?>
Now your script has these variables available: $foo, $bar... It's quite useless and potentially dangerous but it does what you seem to need.
You are trying to use a language construct in a manner in which it's not meant to be used. Use variable variables as Alvaro mentioned.
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
foreach ($arr as $index => $key) {
$$key = $data[$index];
}
or
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$result = array();
foreach ($arr as $index => $key) {
$result[$key] = $data[$index];
}
extract($result);
In short, do not use "list", use arrays and associated arrays. Write helper functions to make your code clearer.
why not immediatly call the vars like
$arr['foo']
or
$arr[0]
If you want to extract the elements of $data into the current context, you can do that with extract. You might find it useful to call array_intersect_key first to pare down $data to the elements that you want to extract.
May be try like this :
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$data = "$".implode(",", $arr);
echo str_replace(",", ",$", $data);

Categories