Check if an array value exist - php

$city = $_GET['cityselect'];
add_query_arg( array ( 'city' => $city, 'key' => 'value' );
Basically i want to check if $city exists and if not i want to remove both key and value, ie 'city' => $city, (comma included). So the output would be:
add_query_arg( array ( 'key' => 'value' );
Any idea?

Only add the city key if it is set, like this:
$arg = array( 'key' => 'value');
if( isset( $_GET['cityselect']))
$arg['city'] = $_GET['cityselect'];
add_query_arg( $arg);

try this
$data = array();
if(isset($_GET["cityselect"])){
$data["city"] = $_GET["cityselect"];
}
add_query_arg($data); // ..

For the short but ugly one-liner version:
add_query_arg($args = (!empty($_GET['cityselect'])) ? array('city' => $_GET['cityselect'], 'key' => 'value') : array('key' => 'value');
Slightly more elegant:
if(!empty($_GET['cityselect']))
add_query_arg(array('city' => $_GET['cityselect'], 'key' => 'value'));
else
add_query_arg(array('key' => 'value'));
Have assumed use of empty, but substitute for isset if applicable to your circumstances.

If you're attempting to remove city if it doesn't exist, you could do:
$city = isset($_GET['cityselect']) ? $_GET['cityselect'] : null;
if (empty($city)) unset($yourArray['city']);
This assumes you already have an array, $yourArray, pre-defined with a city index.
I would recommend to only insert the city index after you've verified it though, such as:
if (isset($_GET['cityselect']) && !empty($_GET['cityselect'])) {
$yourArray['city'] = $_GET['cityselect'];
}
UPDATE: You could also use array_filter() to remove all indexes with missing values after you're done populating it:
$yourArray = array_filter($yourArray);
This will return an array with all empty values stripped; In your case, if city is empty it will be removed from the array.

You can use array_search() (Searches the array for a given value and returns the corresponding key if successful).

Related

How to auto-generate array key values if they are null (from a query)

My application uses many arrays, and many sql queries. My issue is within this code:
I execute this query:
$select = "SELECT name, surname FROM table"
$query = $connection->query($select);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
Then, I pass the values into an array like this:
$array_dump= array(
array(
array('name' => 'name'),
array('content' => $array['name'])
),
array(
array('name' => 'surname'),
array('content' => $array['surname'])
),
)
In fact, this works properly, if you don't set error_reporting(). If I turn on, I get this error:
Notice: Undefined index: surname in C:\AppServ\www\test.php on line 27
This actually happens, due the array was not set. In other words, surname value is empty.
My trouble:
I must use this methodology, but I can't use something like this (got error):
array(
array('name' => 'name'),
array('content' => (isset($array['surname']) ? $array['surname'] : '')
)
My question
As you see, this ain't an error properly, but that "Notice" should not appear (as INDEX is not defined...). Is there any way to set ALL array keys by default, from that query, even if the values are NULL, such as "surname" field? That would be the fastest solution. I've been looking for this, but got no answer.
Thanks!
You should be iterating over the results and formatting them as necessary. Something like this:
$array = $query->fetchAll(PDO::FETCH_ASSOC);
$array_dump = array();
foreach ( $array as $person ) {
$tempArray = array();
array_push($tempArray, array(
'name' => 'name',
'content' => $person['name']
));
array_push($tempArray, array(
'name' => 'surname',
'content' => $person['surname']
));
array_push($array_dump, $tempArray);
}
There is no way to set ALL possible array keys by default. But you can build array of default values based on predefined set of keys and merge it with main array. Somehow like this:
$a_keys = array('name', 'surname');
$a_defaults = array_combine($a_keys, array_fill(0, count($a_keys), 0));
$array = array_merge($a_defaults, $array);
...

How to define an array element using a PHP variable

community.
I've been looking for an answer, but not close enough to this scenario
I have a code like this (actually working fine):
array('desc'=>'Home')
It is working defining it as text (Home) but I would rather to use it as a PHP variable due multilanguage site. Using the language package I have a variable such:
$lang['HOME'] = 'Home';
So depending on the language selected, the value changes
In other words, I need the array to have the variable value as the element
array('desc'=>'variablehere')
Can anyone plese let me know what am I missing? I have tried to set it as variable, as echo and so other ways.
Thanks a lot!
Like this?
$myArray = array('desc' => $variable);
or
$myArray = array(
'desc' => $desc,
'name' => $name
);
In your case:
$lang = array('HOME' => $homeVariable);
Use a multi-dimensional array. e.g., given something like
$lang = 'en';
$key = 'desc';
The exact array structure depends on your needs, but it could either be primarily by language, or by key-to-translate:
language-based:
$translations = array(
'en' => array('desc' => 'foo'),
'fr' => array('desc' => 'bar')
);
$text_to_display = $translations['en']['desc']; // produces 'foo'
or
$translations = array(
'desc' => array(
'en' => array('desc' => 'foo'),
'fr' => array('desc' => 'bar')
)
)
$text_to_display = $translations['desc']['fr']; // produces 'bar'
Use a translate function instead:
// It can be key-based, i.e., t('home_string'), or literal like below
t('Home');
function t($text, $language = NULL)
{
if (!$language) {
// determine visitor's language
}
// look up translation in db/file
// if none found just return $text as is
}

If/Else Ternary Operator with Blank Else Statement Issue

Usually I can get away with using something like:
$a = ($condition)? array(1,2,3) : '';
But now I have a method that accepts a multidimensional array and I must pass or not pass one of the arrays conditionally.
$this->mymethod(
'myarrays'=> array(
array('key' => 'lang_code'),
array('key' => 'lang_description'),
array('key' => 'lang_direction'),
($mycondition==true)? array('key' => 'lang_export') : ),
)
);
Basically, the issue is with the last array passed. And more specifically the ELSE statement in the ternary If operator. It seems that I can't pass simply a blank space after the : and I can't pass anything else like FALSE or '' (empty string), because later on in the code the foreach that runs through this array gives errors.
My question is:
How to pass a parameter to a function/method based on a condition?
array_filter(array(
array('key' => 'lang_code'),
array('key' => 'lang_description'),
array('key' => 'lang_direction'),
$mycondition ? array('key' => 'lang_export') : null),
));
This will remove the null
Use:
$mycondition? array('key' => 'lang_export') : null
Now, you could simply run it through array_filter(..), to remove that NULL element.
Aim for readability, not for how can you type less. The ternary operator is great because in certain cases it increases readability. This is certainly not that case.
Be nice to the people reading your code later, including yourself.
Here is an example (comments are the thoughts of the future reader):
//OK, so here we have an array
$array = array(
array('key' => 'lang_code'),
array('key' => 'lang_description'),
array('key' => 'lang_direction'),
);
//So the array can have one more element based on this condition
if ($mycondition) {
$array[] = array('key' => 'lang_export');
}
//And then we pass this array to the method
$this->mymethod(array('myarrays' => $array));
You are free to use variables and don't have to write all your code in one statement (well, I must admit I thought that was cool earlier).
You could evaluate the condition before the function call, e.g. with a helper-function:
function evaluate_condition (array $mandatory, array $optional, $condition) {
if (true === $condition) {
$mandatory[] = $optional;
}
return $mandatory;
}
$this->mymethod(
'myarrays'=> $this->evaluate_condition(
array(
array('key' => 'lang_code'),
array('key' => 'lang_description'),
array('key' => 'lang_direction')
),
array('key' => 'lang_export'),
$mycondition
)
);

Add some logic in array filing

I'm trying to fill an array and I want to add some logic in it so it won't give me back errors...
Here is the code:
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}
what I want to do is to be able to check if some of the variables exist before I put them into the array....
so for example if(isset($mix['name'])) then insert to array or else do nothing
The point is not having undeclared variables trying to be inserted to my array cause it gives back errors...thanks!
You can use the ? : ternary operator:
$entries_mixes[] = array(
'title' => (isset($entry['title']) ? $entry['title'] : null),
'author' => (isset($entry['author']) ? $entry['author'] : null),
...
alternatively, use empty() for the check
You could use the ternary operator so that if the variables don't exist, NULL is used as the value. But you actually want to omit certain keys from the array altogether in that case. So just set each key separately:
$entry[] = array();
...
if (isset($mix['name'])) {
$entry['mix_name'] = $mix['name'];
}
...
$entries_mixes[] = $entry;
The following will check if title doesn't exists in the entry array or if it's blank. If so, it'll skip the entry completely and continue to the next element in the loop.
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
if (empty($entry['title'])) {
continue;
}
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}

Need help about array

What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.

Categories