Key "1" for array with keys "0, +, -" does not exist - php

I have swapped an array around in order to fix this deprecation;
The value "false" for the "choices_as_values" option of the "choice"
form type (Symfony\Component\Form\Extension\Core\Type\ChoiceType) is
deprecated since version 2.8 and will not be supported anymore in 3.0.
Set this option to "true" and flip the contents of the "choices"
option instead.
But now I am getting the following error;
Key "1" for array with keys "0, +, -" does not exist in
src/MyBundle/Resources/views/Consult/show.html.twig at line 467
This is my function/array after swapping the key and value around;
public static function enumZeroPlusMinus()
{
return array(
'0' => '0',
'+' => '1',
'-' => '2',
);
}
and this is my the line the new error complains about;
<td>{{ entity.enumZeroPlusMinus[entity.foreFootSupportLeft] }}</td>
I don't understand the error. Can somebody perhaps explain and help me with this one? It is probably something small. Or could it be that Doctrine has an issue? Because the '0', '1', and '2' is the values stored in the database. Thanks!

Your array doesnt have a key 1, it has '0', '+', '-'.
Unless Ive misunderstaood, you need to do something like this:
$array = enumZeroPlusMinus();
echo $array[ array_search('1', $array) ];
also, just throw your original array through array_flip when trying to deal with the deprecation warning.

Related

fast way compare value of two array of object php [duplicate]

Hi i want to compare all the values of 2 arrays and end up with a true or false . I am using the code below and would of thought that the result would be false . but that is not the case , when the last line runs I would expect a display something like
Array ( [0] => 0 )
but I get no display so assume that php is happy that there is no difference
my code is
$before = array('1', '1', '0', '0', '1', '0' ) ;
$after = array('0', '1', '0', '0', '1', '0' ) ;
$new_array= array_diff($before,$after);
print_r ($new_array) ;
surely the array_diff should spot a difference here ? any help would be great thanks
array_diff gives which elements are in $before but not $after. Since both arrays consist of '0' and '1', it returns an empty array.
What you're looking for is array_diff_assoc, which looks at keys and values together.
Do note, the output you get will not be Array( [0] => 0 ), but rather Array( [0] => 1 ), as it gives the elements from the first array that doesn't exist in the other one.
If you wish the other output, you'll need to do array_diff_assoc($after, $before).
$before = array('1', '1', '0', '0', '1', '0' ) ;
$after = array('0', '1', '0', '0', '1', '0' ) ;
$new_array= array_diff_assoc($before,$after);
print_r ($new_array) ;
See http://php.net/manual/en/function.array-diff.php
"Multiple occurrences in $array1 are all treated the same way."
So, since all you have a zeros and ones, everything is "the same."
Yes, array_diff does spot a difference. It finds the differences between the following arrays with the first one. It doesn't compare 0 to 0 and 1 to 1, however. It simply checks if each value in Array1 is in Array2 ... ArrayN. This function returns an array of all the occurrences in Array1 that were not found in the other arrays, not a true/false boolean. See example 1 in the documentation.
Hi i want to compare all the values of
2 arrays and end up with a true or
false
$bool = ($array1 == $array2);
http://us2.php.net/manual/en/language.operators.array.php
It might sound silly, but comparing two array of different lengths will NOT yield expected difference. Check the length of the arrays first and if they match then use array_diff. Otherwise your diff will always be empty.

array_diff() strange behaviour

I have a routine in my code that computes the differences between two arrays in order create an SQL UPDATE statement.
As soon the routine starts I create a copy of the input array in order to manipulate it while the input one is kept untouched. When I'm ready to create the UPDATE statement I compute the difference between them, using the modified array as leading one.
In every test I ran both arrays were filled with key=value pairs and all values were strings, even when they're integers in the database (PDO behavior) and until now everything worked flawlessly.
But right now I've found something strange. Two different actions, in two different Controllers, but with the same logic are producing different differences:
This one works as expected:
$input = array(
'tid' => '3',
'enabled' => '1'
);
$modified = array(
'tid' => '3',
'enabled' => 0,
'modified' => '2014-11-26 15:17:55'
};
$diff = array(
'enabled' => 0,
'modified' => '2014-11-26 15:17:55'
);
$input is the result of a query. $modified is a copy of the first array manipulated through class methods. When I'm ready to create the statement, $diff is computed in order to send to PDO (or other driver) the correct statement.
Here, array_diff() works. the tid index is present in both array and it's ignored. The enabled, a simple on/off flag, is different and it's included. The datetime representation too.
But look the variables of this other case:
$input2 = array(
'sid' => '1',
'finished' => '0'
);
$modified2 = array(
'sid' => '1',
'finished' => 1,
'modified' => '2014-11-26 15:21:58'
);
$diff2 = array(
'modified' => '2014-11-26 15:21:58'
);
The same as before but with different field names. The sid is ignored but the finished is ignored too while it shouldn't because it is not present in the $input.
By replacing array_diff() with array_diff_assoc(), as expected, everything works, but why?
From the docs:
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
In your example, $modified2 has an entry 'finished' which has value 1. But $input2 also has value 1 for key 'sid'. Thus, using array_diff($modified2, $input2) will result in the removal of every entry with value 1, no matter what the key is.
Using array_diff_assoc, it will only check to see if $input2 has the entry 'finished' => 1, which it does not, so the entry will not be removed.

PHP isset returns true but should be false

My project is in cakePHP but I think this is an aspect of native PHP that I am misunderstanding..
I have an afterFind($results, $primary = false) callback method in my AppModel. On one particular find if I debug($results); I get an array like this
array(
'id' => '2',
'price' => '79.00',
'setup_time' => '5',
'cleanup_time' => '10',
'duration' => '60',
'capacity' => '1',
'discontinued' => false,
'service_category_id' => '11'
)
In my afterFind I have some code like this:
foreach($results as &$model) {
// if multiple models
if(isset($model[$this->name][0])) {
....
The results of the find are from my Service model so inserting that for $this->name and checking if(isset($model['Service'][0])) should return false but it returns true? if(isset($model['Service'])) returns false as expected.
I am getting the following PHP warning:
Illegal string offset 'Service'
so what's going on here? why does if(isset($model['Service'][0])) return true if if(isset($model['Service'])) returns false?
UPDATE:
I still don't know the answer to my original question but I got around it by first checking if $results is a multidimensional array with
if(count($results) != count($results, COUNT_RECURSIVE))
Use array_key_exists() or empty() instead of isset(). PHP caches old array values strangely. They have to be manually unset using unset()
isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.
String offsets provide a mechanism to use strings as if they were an array of characters:
$string = 'abcde';
echo $string[2]; // c
$model is indeed a string for all keys except discontinued.
As for the isset($model['Service'][0]) return value, I'm a bit surprised. This is a simplified test case:
$model = '2';
var_dump(isset($model['Service'])); // bool(false)
var_dump(isset($model['Service'][0])); // bool(true)
There must be a reason somewhere. Will have a dig..

Can an array key be a string with embedded zero bytes?

Can an array key in PHP be a string with embedded zero-bytes?
I wanted to implode a multi-part key with embedded zero-bytes as the delimiter and use it as the key in an associative array, but it doesn't seem to be working. Not sure whether this is a problem with the array access or with array_keys_exists().
Does anybody have any idea? Am I going about this the wrong way? Should I be creating a multi-part key in another way?
To clarify, I am trying to eliminated duplicates from user-entered data. The data consists of a product ID, a variation ID, and N fields of textual data. Each of the N fields has a label and a value. To be considered a duplicate, everything must match exactly (product ID, variation ID, all the labels and all the values).
I thought that if a create a string key by concatenating the information with null bytes, I could keep an associative array to check for the presence of duplicates.
From the PHP string documentation:
There are no limitations on the values the string can be composed of;
in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere
in the string (however, a few functions, said in this manual not to be
“binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
From the PHP arrays documentation:
A key may be either an integer or a string.
No mention is made of any special case for strings that are array keys.
So, yes.
Like I already said in the comments
print_r(array("\00foo\00bar" => 'works'));
works. However, there is no reason for any of the gymnastics you are doing with implode or serialize or null byte keys.
If you want to see whether arrays are identical, then you can just compare them:
$input1 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
$input2 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar');
var_dump($input1 === $input2);
will output true whereas
$input3 = array('product_id' => 1, 'variation_id' => 2, 'foo' => 'foobarbaz');
var_dump($input1 === $input3);
will give false.
Quoting the PHP Manual on Array Operators:
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Also, PHP has a function for deleting duplicate values from arrays:
array_unique — Removes duplicate values from an array
And when you set the second argument to SORT_REGULAR, PHP will compare the arrays for equality, e.g.
$data = array(
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 1, 'variation_id' => 2, 'foo' => 'bar'),
array('product_id' => 2, 'variation_id' => 2, 'foo' => 'bar')
);
print_r(array_unique($data, SORT_REGULAR));
will reduce the array to only the first and the third element.

Compare to values of two arrays in PHP

Hi i want to compare all the values of 2 arrays and end up with a true or false . I am using the code below and would of thought that the result would be false . but that is not the case , when the last line runs I would expect a display something like
Array ( [0] => 0 )
but I get no display so assume that php is happy that there is no difference
my code is
$before = array('1', '1', '0', '0', '1', '0' ) ;
$after = array('0', '1', '0', '0', '1', '0' ) ;
$new_array= array_diff($before,$after);
print_r ($new_array) ;
surely the array_diff should spot a difference here ? any help would be great thanks
array_diff gives which elements are in $before but not $after. Since both arrays consist of '0' and '1', it returns an empty array.
What you're looking for is array_diff_assoc, which looks at keys and values together.
Do note, the output you get will not be Array( [0] => 0 ), but rather Array( [0] => 1 ), as it gives the elements from the first array that doesn't exist in the other one.
If you wish the other output, you'll need to do array_diff_assoc($after, $before).
$before = array('1', '1', '0', '0', '1', '0' ) ;
$after = array('0', '1', '0', '0', '1', '0' ) ;
$new_array= array_diff_assoc($before,$after);
print_r ($new_array) ;
See http://php.net/manual/en/function.array-diff.php
"Multiple occurrences in $array1 are all treated the same way."
So, since all you have a zeros and ones, everything is "the same."
Yes, array_diff does spot a difference. It finds the differences between the following arrays with the first one. It doesn't compare 0 to 0 and 1 to 1, however. It simply checks if each value in Array1 is in Array2 ... ArrayN. This function returns an array of all the occurrences in Array1 that were not found in the other arrays, not a true/false boolean. See example 1 in the documentation.
Hi i want to compare all the values of
2 arrays and end up with a true or
false
$bool = ($array1 == $array2);
http://us2.php.net/manual/en/language.operators.array.php
It might sound silly, but comparing two array of different lengths will NOT yield expected difference. Check the length of the arrays first and if they match then use array_diff. Otherwise your diff will always be empty.

Categories