PHP in_array isn't finding a value that is there - php

I have an array called $friend_array. When I print_r($friend_array) it looks like this:
Array ( [0] => 3,2,5 )
I also have a variable called $uid that is being pulled from the url.
On the page I'm testing, $uid has a value of 3 so it is in the array.
However, the following is saying that it isn't there:
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.
What am I doing wrong? Any help would be greatly appreciated!

Output of
Array ( [0] => 3,2,5 )
... would be produced if the array was created by something like this:
$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);
Based on your question, I don't think this is what you meant to do.
If you want to add three values into the first three indexes of the array, do the following:
$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');
or, as a shorthand for array_push():
$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';

Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:
// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
}
Working example

Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.
Example:
$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;
Your above if statement will then work correctly.

Related

Pushing an Array element into an existing multidimensional array in codeigniter

I have a query in codeigniter like this
$query_tutors = $this->db->get_where("tutor_info", array('tutor_id' => $tutor_id));
I have also other array elements that I want to pass in the query which depends on some conditions.
So how do I push other multidimensional array elements to the existing array so I can pass the variable as a whole in the query?
array_push is not working in this case.
$array = array();
$array = array("tutor_id" => $tutor_id);
$array = array("online" => $online); // want to merge this to the 1st array.
$query_tutors = $this->db->get_where("tutor_info", $array);
First you're doing it wrong.
$array = array();
$array = array("tutor_id" => $tutor_id);
You're recreating the array again, which will delete it from the memory. Either you have to use
$array['tutor_id'] = $tutor_id;
$array["online"] = $online;
or
$array = array('tutor_id' => $tutor_id, 'online' => $online);
or if you want to merge two arrays
$array = array_merge(array('tutor_id' => $tutor_id), array('tutor_id' => $tutor_id));
Your initial code
$array = [];
$array = ["tutor_id" => $tutor_id];
Now, if you want to add conditional merge, simply follow,
if($condition)
{
$array = array_merge($array, ["online" => $online]);
}
If $condition == true You final array will be,
$array = ['tutor_id' => $tutor_id, 'online' => $online];
You are almost there, just need to read a little bit more about associative arrays.
Solution:
$array = array();
$array["tutor_id"] = $tutor_id;
$array["online"] = $online;
$query_tutors = $this->db->get_where("tutor_info", $array);
This way your $array will have all indexes which you want.
You can do something like this:
$array = array();
if (!empty($tutor_id))
{
$array["tutor_id"] = $tutor_id;
}
if (!empty($online))
{
$array["online"] = $online;
}
$query_tutors = $this->db->get_where("tutor_info", $array);

Separating two arrays returned from mysqli_fetch_array

I have created this
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
print_r($data['course']);
}
Which prints this:
Array (
[user_id] => 57
[course] => 6
)
Array (
[user_id] => 57
[course] => 5
)
How can I create two variables that are equal to the values of the 'course' fields.
So ideally, variable x ends up equalling to 6 and variable y equals 5 (essentially what I'm asking is how to extract the value from the mysql arrays and putting it into a variable)?
There is no something as you called "mysql_arrays". They are normal arrays.
You can do for example:
$array = array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$array[] = $data; // probably this way and not $array[] = $data['course'];
}
$x = $array[0]['course'];
$y = $array[1]['course'];
I would suggest you using an array instead of a variable to store the values.
$arr= array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$arr[] = $data['course'];
}
Speculating a bit as don't have the full picture but I guess you're after something like this.
Get an array of the courses from your data
$data = array_map(function($value) {
return $value['course'];
}, $data);
If there are only ever two results, assign each one to a variable :
list($x, $y) = $data;
If there are more than two results, you have an array of courses in $data from your query results.

Take the value from array in php and explode

I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.
Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}
When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.
Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}

Join string and variable to get another variable in PHP

Sorry if this has already been asked, but it's hard to search for it... I tried googlin this topic without success.
What I want to do is this:
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo $chosenTheme [0];
I want to join the $layoutColor variable with the word "colors" in order to get the variable $colors2.
How do I do that?
Thanks.
You're best off approaching this by just combining all your options into a single multi-dimensional array:
$layoutColor = 2;
$colors = array();
$colors[1] = array ("F57171", "FACCCC");
$colors[2] = array ("FF9900", "FFC66F");
$chosenTheme = $colors[$layoutColor];
echo $chosenTheme [0];
Try this:
<?php
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo ${$chosenTheme}[0];
Prints:
FF9900
I think you can simplify this using multi dimensional arrays:
$colors = array(
array ("F57171", "FACCCC"),
array ("FF9900", "FFC66F")
);
So...
echo $colors[0];
Or you can user variable variables:
$chosenTheme = ${"colors".$layoutColor};
You may try this
$layoutColor = 2;
$$colors2 = "colors".$layoutColor;
So you'll get $colors2 variable
print_r($colors2); // Array ( [0] => FF9900 [1] => FFC66F )
Notice the double $, that will keep the variable name in the variable.
Try with:
$layoutColor = 2;
$string = "color";
echo $$string.$layoutColor;
You need to use dynamic variables
$$chosenTheme = "colors".$layoutColor;
then access the array by using this variable
$chosenTheme
This might not be an answer to your question but, depending on your specific context, try something like this:
$layoutColor = 2;
$colors = array (
Array("F57171", "FACCCC"),
Array ("FF9900", "FFC66F")
);
echo $colors[$layoutColor][0];
A multi dimensional array is a lot easier to read

Array not populating correctly

I am using the following code to populate an array:
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
postcodeUnknown returns the first row from a mysql query, using a table prefix and an element from an array named postcodes. $postcodes contains strings that should return a different row each time though the loop.
Which I'd expect to create an array similar to:
Array ([0] =>
Array ([0] => some data [1] => more data)
[1] =>
Array ([0] => second row [1] => even more...)
)
But it's not. Instead it's creating a strange array containing the first results over and over until the condition is met, eg:
simplified result of print_r($ref);
Array (
[0] => Array ([0] => some data [1] => more data)
)
Array(
[0] => Array (
[0] => the first arrays content...
[1] => ...repeated over again until the loop ends
)
)
And I'm at a loss to understand why. Anyone know better than me.
Try
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref1[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref2[] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref3[$count][] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
echo "<pre>";
print_r($ref1);
print_r($ref2);
print_r($ref3);
echo "</pre>";
Try that to see if any of those get an output you are looking for.
Uh, add a print to postcodeUnknown and check if its actually passing different postcodes or the same thing all the time?
ie
function postcodeUnkown($a,$b){
echo var_dump($a).var_dump($b);
//the rest
}
Also, why two different variables? ($quantitys and $postcodes).
Also, you might want to replace the while loop with for:
for($i=0;$i<$number;$i++){
$ref[$i] = postcodeUnknown ($prefix, $postcodes[$i]);
}
your variable count should not be a string, try this
$number = count ($quantitys);
$count = 0;
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}

Categories