PHP in_array not returning expected results - php

When I attempt to determine if a user is in an array of users, for some reason it is only returning true when the user is in the 0th position.
For the life of me I cannot figure out what I am doing wrong.
This does not echo "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => JKB [1] => RDW )
if(in_array($usersign,$these_analysts[0])){
echo "True";
}
This echoes "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => RDW [1] => CLM )
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
EDIT:
vardump gives a much more comprehensive view of the array, whereas print_r did show the trailing spaces, it didn't catch my eye.
For some reason the first element of each array was giving string3, and all others were giving string4.

You have a lot of syntax errors.
When you use strings, it is always better prace to put strings in single or double quotes. It doesn't matter which one (as far as speed is concerned).
Also, you need commas between the elements.
I entered the following code and it works.
$usersign = 'RDW';
$these_analysts[0] = array( 'JKB', 'RDW' );
print_r( $these_analysts );
if(in_array($usersign,$these_analysts[0])) echo "True";

Try:
$usersign = 'RDW';
$these_analysts[1] = Array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
That should work.

This is happening (at least in my testing) if you specify RDW as a constant without defining these constants before using them. If you put your initials in double-quotes (i.e. use explicit strings) then everything works fine. If you want to use them as constants, then define these constants first:
define("RDW","RDW");
define("JKB","JKB");
And then your code works as expected again.

You're missing ; on half of your lines, you're using base strings instead of " around them, and your Array syntax is invalid (should be Array("JKB","RDW");). Maybe if these are fixed it might have a chance of working.

You have punctuation errors:
$these_analysts[0] = Array ( [0] => JKB [1] => RDW )
should be
$these_analysts = Array ( 0 => "JKB", 1 => "RDW" );

*This is the actual way you need to do *
$usersign = 'RDW';
$these_analysts = array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts)){
echo "True";
}

Related

$$array[0] returns array name letter and not array value

I would like to use the first value of a dynamically created array but I get the first letter of the array name instead.
$log = "dets_".$id;
$$log = array();
while ($c = mysql_fetch_assoc($cuenta)) { array_push($$log,$c['id'].'::'.$c['fecha']); }
When I print $$log I get something like this:
Array ( [0] => 124::2017-04-07 [1] => 119::2017-04-07 [2] => 118::2017-04-05 )
But when I try to access the first key:
echo $$log[0];
I get "$d" and not "124::2017-04-07". I also tried $log[0] and get "d".
Thank you.
You could access the first element by somewhat tricky expression:
var_dump (${${'log'}}[0]);
http://php.net/manual/en/language.variables.variable.php
A bit of explanation Taken from PHP Manual
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.

Php array_rand() printing variable name

I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];

PHP - Undefined offset (0) even though it holds a value

I'm trying to work in a CodeIgniter environment and while trying to collect and gather some information into variables I'm getting some PHP NOTICE errors that don't seem right.
Here's the chunk of code where the error(s) occur:
if (empty($events['user'][$user_id])) {
unset($events['user'][$user_id]);
} else {
foreach ($events['user'][$user_id] as $event) {
$events['user'][$user_id]['events']['event_id'] = $event_id = $event['event_id'];
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
$events['user'][$user_id]['event']['request_title'] = $event['request_title'];
$events['user'][$user_id]['event']['event_status_text'][] = $this->events_model->getEventStatusFromSectionStatuses($event_id);
$request_data = $this->requests_model->getRequestInfo($event['request_id']);
$events['user'][$user_id]['event']['ministry'] = $this->ministries_model->getMinistryTitle($request_data[0]['requesting_ministry']);
// more stuff will go here...
}
$content_data['event_status_text'] = $events['user'][$user_id]['event_status_text'];
$content_data['events'] = $events['user'][$user_id]['complete_events'];
$content_data['totals'] = $events['user'][$user_id]['totals'];
$content_data['updated_events'] = $events['user'][$user_id]['updated_events'];
}
The specific line of the first error is the third line inside the foreach loop that ends with ['date'][0]['date']. It's the [0] that PHP is telling me is undefined. However, if I echo that exact same variable like this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
...it outputs a value as would be expected, which also tells me that the [0] is NOT undefined after all. I'm not actually changing the variable. The only difference is that I'm echoing it instead of assigning it to another variable.
If I use # to ignore it in here, it happens again a few lines later on the line ending with getMinistryTitle($request_data[0]['requesting_ministry']).
Can you see what I'm doing wrong? Let me know if you need to see more of the code.
Here's the getEventDates() code as requested (note this is not my code):
function getEventDates($event_id)
{
$sql = "SELECT date FROM `event_dates` WHERE event_id=? ORDER BY date";
$res = $this->db->query($sql, array($event_id));
return $res->result_array();
}
if I print out $this->events_model->getEventDates($event_id) I get the following:
Array
(
[0] => Array
(
[date] => 2014-05-01
)
[1] => Array
(
[date] => 2014-05-08
)
[2] => Array
(
[date] => 2014-05-15
)
[3] => Array
(
[date] => 2014-05-22
)
[4] => Array
(
[date] => 2014-05-29
)
[5] => Array
(
[date] => 2014-06-05
)
[6] => Array
(
[date] => 2014-06-12
)
)
Hmmm... is it possible that this error is happening because there isn't a direct value contained in [0], but rather another array level? Please note that I did not structure this output. Someone else coded this and it's just my job to come in and work with it.
Without seeing the rest of your code this is confusing:
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
Why would you be setting $events['user'][$user_id]['event']['date'] in one line and then in the next overriding it again?
My best advice would be to set the first assignment in a variable independent of the array, and then calling that variable for the data:
$event_dates_temp = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
And perhaps adding a conditional check to ensure you are setting things that exist:
$event_dates_temp = $this->events_model->getEventDates($event_id);
if (array_key_exists(0, $event_dates_temp)) {
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
}
Also, it’s unclear at what point you are doing this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
And what is the output when you do dump like this:
echo '<pre>';
print_r($events['user'][$user_id]['event']['date']);
echo '</pre>';
It happens when you are trying to access a value which is not set for that index, please read this link for more information.
There are two options available:
Ignore these notices by telling the PHP error_reporting to not show notices error_reporting(E_ALL ^ E_NOTICE); but it is a good practice to fix this error by adding a check if a value exists.
Fix the values by isset function to see if the value/index contains any data.
If You hide notice set error_reporting(E_ALL ^ E_NOTICE);
Solution is use isset() to solved this issue.

Cleaner way to echo multi dimension array

echo "{$line['text_1']}";
the above echo works fine ,however when it comes to 2d array, in my sublime, only {$line['text_2']} this part work fine. output error both sublime and browser
echo "$array_2d[{$line['text_1']}][{$line['text_2']}]";
any idea?
update
echo "$array_2d[$line['text_1']][$line['text_2']]";
using xampp, error Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs
and I'm just outputting a value from the mysql_fetch_assoc. I can do it in another way by echo '' however I'm trying to make my code easier for future editting and code copy paste
and yes I'm doing things like
echo "The price is $array_2d[$line['text_1']][$line['text_2']]"
with lots of html code in the double quote.
Why are you trying to output the array?
if it is for debugging purposes, you can just use the native php functions print_r() or var_dump()
You should be able to say
echo "item is {$array_2d[$line['text1']][$line['text2']]}";
to get to a subelement.
Of course, this is only really useful when it's not the only thing in the string. If you're only echoing the one value, you don't need the quotes, and things get simpler.
echo $array_2d[$line['text1']][$line['text2']];
this should work :
echo $array_2d[$line['text_1']][$line['text_2']];
When echoing variables, you don't have to use the quotes:
echo $array_2d[$line['text_1']][$line['text_2']];
If you do need to output something with that string, the concatentation operator can help you:
echo "Array: " . echo $array_2d[$line['text_1']][$line['text_2']];
You can use print_r() to echo the array.
e.g.:
print_r($array);
Output will be:
Array ( [test] => 1 [test2] => 2 [multi] => Array ( [multi] => 1 [multi2] => 2 ) )
Also you can use this to make it more readable in a HTML context:
echo '<pre>';
print_r($array);
echo '</pre>';
Output will be:
Array
(
[test] => 1
[test2] => 2
[multi] => Array
(
[multi] => 1
[multi2] => 2
)
)
You can use print_r() or var_dump() to echo an array.
The print_r() displays information about a variable in a way that's readable by humans whereas the var_dump() function displays structured information about variables/expressions including its type and value.
$array = 'YOUR ARRAY';
echo "<pre>";
print_r($array);
echo "</pre>";
or
$array = 'YOUR ARRAY';
var_dump($array);
Example variations
I'm wondering why you would try using the $line array as a key to access data in $array_2d.
Anyway, try this:
echo($line['text_1'].'<br>');
this:
echo($array_2d['text_1']['text_2'].'<br>');
and finally this (based on your "the $line array provides the keys for the $array_2d" array example)
$key_a = $line['text_1'];
$key_b = $line['text_2'];
echo($array_2d[$key_a][$key_b].'<br>');
Which can also be written shorter like this:
echo($array_2d[$line['text_1']][$line['text_2']].'<br>');
Verifying/Dumping the array contents
To verify if your arrays hold the data you expect, do not use print_r. Do use var_dump instead as it will return more information you can use to check on any issues you think you might be having.
Example:
echo('<pre>');
var_dump($array_2d);
echo('</pre>');
Differences between var_dump and print_r
The var_dump function displays structured information of a variable (or expression), including its type and value. Arrays are explored recursively with values indented to show structure. var_dump also shows which array values and object properties are references.
print_r on the other hand displays information about a variable in a readable way and array values will be presented in a format that shows keys and elements. But you'll miss out on the details var_dump provides.
Example:
$array = array('test', 1, array('two', 'more'));
output of print_r:
Array
(
[0] => test
[1] => 1
[2] => Array
(
[0] => two
[1] => more
)
)
output of var_dump:
array(3) {
[0]=> string(4) "test"
[1]=> int(1)
[2]=> array(2)
{
[0]=> string(3) "two"
[1]=> string(4) "more"
}
}

PHP Fatal error: Cannot use string offset as an array

Facing a weird situation with arrays..
I am using LinkedIn API to get profile info which returns data in two formats..
If user has just one educational item
educations=>education=>school-name
educations=>education=>date
...
If more than one education item
educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...
Now I am trying to make it consistent and convert
educations=>education=>school-name
to
educations=>education=>0=>school-name
But getting error in code that i believe should work
if(empty($educations['education'][0]['school-name']))
{
$temp = array();
$temp['education'][0]=$educations['education'];
$educations = $temp;
}
This fails for "just one educational item", generates error on the first line for (isset,is_array and empty)
PHP Fatal error: Cannot use string offset as an array in ...
print_r returns
[educations] => Array
(
[education] => Array
(
[id] => 109142639
[school-name] => St. Fidelis College
[end-date] => Array
(
[year] => 2009
)
)
)
Usually you'd write the assignment like this:
$temp = array(
"education" => array($educations['education'])
);
To avoid any issues with indexes. This might also fix yours.
If you're unsure about the contents of $educations['education'][0]['school-name'] you can simply check each part:
if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))
This works because isset doesn't behave like a normal function. It takes multiple arguments in a lazy manner.
You want:
if(array_key_exists('school-name',$educations['education']))
{
$educations['education'] = array($educations['education']);
}
Today I experienced the same problem in my application. Fatal error: Cannot use string offset as an array in /home/servers/bf4c/bf4c.php on line 2447
line 2447
if (!isset($time_played[$player]["started"])) {
$time_played[$player]["started"] = $time;
}
$time_played was overwritten elsewhere and defined as a string. So make sure you do use unique variable names.
Here's a tip if you're running through a loop, and it breaks:
if( $myArray != "" ){
// Do your code here
echo $myArray['some_id'];
}

Categories