Dynamically check for strings in a PHP array - php

EDIT: ten months later, I'm still back to this.. still can't figure it out :(
I can search for a string in an array no problem; this works:
if (in_array('animals', $value[tags])){
echo "yes";
}
But how can I check for a variable in the array? This doesn't seem to work:
$page_tag = 'animals';
if (in_array($page_tag, $value[tags])){
echo "yes";
}
I'm guessing I'm missing some simple syntax doodad?
The array is massive, so I'll try and show a sample of it. It is stored on a separate php file and "included" in other places.
global $GAMES_REPOSITORY;
$GAMES_REPOSITORY = array (
"Kitten Maker" => array (
"num" => "161",
"alt" => "Kitten Maker animal game",
"title" => "Create the kitten or cub of your dreams!",
"tags" => array ("animals", "feline", "cats", "mega hits"),
),
}
Here's a larger part of the code, to put into context. It pulls from the array of ~400 games, and pulls the ones with a specific tag:
function array_subset($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($page_tag, $value["tags"])){
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
return $newArray;
}
function array_copy($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset($GAMES_REPOSITORY);
$games_list = array_reverse($games_list);
Oh, an interesting hint. Elsewhere it DOES work using $_GET:
if (in_array($_GET[tagged], $value[tags])){

The in_array() function can check variables, so it is likely that your problem comes from somewhere else. Verify that you've defined your constant tags correctly. If it's not defined, it might not work depending on your PHP version. Some versions just assume that you wanted to write the string tags instead of a constant named tags.
Your code works. Here's a full example that I've tested that works well:
<?php
const tags = "tags";
$page_tag = 'animals';
$value = array('tags' => array("fruits", "animals"));
if (in_array($page_tag, $value[tags])){
echo "yes";
}

You have an array of arrays, so in_array() wont work as you have written it as that test for existence in an array, not a subarray. You may as well just loop through your arrays like this:
foreach($GAMES_REPOSITORY as $name =>$info) {
if(in_array($page_tag, $info['tags']))
{ whatever }
}
If that is not fast enough you will have to cache your tags by looping ahead of time and creating an index of tags.

I finally got it to work! I don't entirely understand why, but I had to feed the variable into the function directly. For some reason it wouldn't pull the variable from the parent function. But now it works and it even takes two dynamic variables:
function array_subset2($arr, $tag1, $tag2) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($tag1, $value['tags'])){
if (in_array($tag2, $value['tags'])){
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
}
return $newArray;
}
function array_copy2($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset2($GAMES_REPOSITORY, $page_tag, $featured_secondary_tag);

Related

How to return all values of an array

I am trying to return all the values of array but this code is acting as as a die statement..so what's the error in this code?
<?php
$search_array = array("first"=> "first_user", 'second' => 4_user);
foreach($search_array as $key => $value )
{
if(array_key_exists($key, $search_array))
{
return $search_array[$key];
}
else
{
echo "not found";
}
}
?>
Your problem is that you're using return from within your loop, which will end the execution of the current scope.
If you want to return all values of that array, you need to push each value to a temporary storage variable and return that at the end of the loop:
$output = array();
foreach ($myArray as $key => $value) {
$output[] = $value;
}
return $output;
That's for your problem. If all you want to do is return the values of an array, you can simply return array_values($search_array). What you're trying to do is a tautological way of doing what this function does already.

How to "skip" iteration when building a new array using recursion

I am stuck on something that might be very simple.
I am creating a new array by looping through an existing array using a recursion function yet I can not seem to get the values to stick to the new array. The function, in the end, will be a bit more complex, but for now I need some help.
I have tried soooo many ways to get this to work but I am at a loss right now.
Here is my php function
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
As is, the new array never gets filled...BUT, if I change this line...
recursive($value); // Why can't I just call the recursive function here?
...to...
$newArray[] = recursive($value); // Instead of having to set a new value to the new array?
everything works properly...except that my goal was to create a flat array with only the values.
So my question is, why is it necessary to set a new array value in order to call the recursive function again? Ideally, I want to skip setting a new array value if the value is an array and just continue the loop through the original array.
Use array_merge:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or you could use special operator:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray += recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or pass a variable by reference like this:
function recursive($array, &$newArray = null) {
if (!$newArray) {
$newArray = array();
}
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value, $newArray);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
use array_merge() to merge the array returned from recursive($value); and $newArray
$newArray = array_merge($newArray,recursive($value));
You can guarantee that $newArray will be flat after this, as the previous value of $newArray was flat, and recursive always returns a flat array, so the combination of both should be a flat array.
You aren't doing anything with the return from your recursive function. Try this:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
// This is what was modified
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}

how to split stored variables name inside foreach

How can i know the variables ?
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
//how to know variables?
$id_???
Currently I know the $value['name'] ie. it may be one,two, three, etc. but how to use them
echo $id_one;
I wanted to know here to split them in an array. So i can use
print_r($vars); which would result $id_one, $id_two, etc..
Something like this?
<?php
$array = [];
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$array[] = $value['id'];
}
}
print_r($array);
You can find variables by code:
foreach (get_defined_vars() as $var_name => $var_value) {
if(strpos($var_name, 'id_') ===0 ){
//it's your variable
}
}
But store variable in local scope look wrong.
May be better store to an other array:
$arIds = array();
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$arIds['id_'.$value['name']] = $value['id'];
}
}

if empty $_POST assign value in foreach loop

Hi want to build a program which creates surveys. I couldn' t figure out how can i assign value for a question which is unanswered. Thank you for your helps.
$dizi = array();
foreach ( $_POST as $key => $value){
if(empty($_POST)){
$_POST="bos";
}
$dizi[$key] = "'".$value."'";
}
Your code doesn't make sense, try this:
$dizi = array();
foreach($_POST as $key => $value) {
if (empty($value)) {
$value = 'your value';
}
$dizi[$key] = $value;
}
$_POST is an associative array
So you can access it with:
$bla = $_POST['bla'];
What you are trying to do is setting the whole array to a string which doesn't work.
You should set the new value when saving it to the $dizi array.
$dizi = array();
foreach($_POST as $key => $value) {
$newValue = $value;
if (empty($value)) {
$newValue = 'bos';
}
$dizi[$key] = $newValue;
unset($newValue);
}
But this only checks if answer string is empty. So this only works if all questions are mandatory.
If I understood you correctly, what you are trying to do is this:
foreach ( $_POST as $key => $value ) {
if(empty($value))
$_POST[$key] = 'This is an unanswered question!';
}
But this cannot work due to the fact that empty values aren't posted from the form.
How do you know that there is 'unanswered' question if it was not posted from the form?
You have to start from the list of the questions (which can not be forged by the user and is defined on the server-side) and check that answer for each of them exists in $_POST. If not - assign whatever you want to the skipped answers.
Try this:
if(isset($_POST) && (!empty($_POST))){
foreach ( $_POST as $key => $value ) {
if(empty($value)){
$_POST="bos";
} else{
//put your code
}
}
}

How to change first char of each key in array?

I have an array with all keys in lover case and i need to change them that the firs char would be in uppercase, like ucfirs function does. Is it possible without creating a new array?
It's not possible without creating a new array, but here's a funky one-liner you could use:
$array = array_combine(
array_map('ucfirst', array_keys($array)),
array_values($array)
);
It breaks up the array into keys and values, transforms the keys and then glues the two pieces back together.
Try this code:
foreach ($array as $key => $value) {
unset ($array[$key]);
$array[ucfirst($key)] = $value;
}
try this
foreach ($arr as $key=>$val){
unset($arr[$key]);
$key = ucfirst($key);
$arr[$key]=$val;
}
try this. it will work for nested array too.
<?php
function ucfirstKeys(&$data)
{
foreach ($data as $key => $value)
{
// Convert key
$newKey = ucfirst($key);
// Change key if needed
if ($newKey != $key)
{
unset($data[$key]);
$data[$newKey] = $value;
}
// Handle nested arrays
if (is_array($value))
{
ucfirstKeys($data[$key]);
}
}
}
$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo'));
ucfirstKeys($test);
print_r($test);

Categories