Unknown php unset error - php

I have problem in deleting an element of array. Look:
<?php
session_start();
$i = 0;
$expected = $_GET['name'];
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
break;
}
$i++;
}
unset($_SESSION['chart'][$i]);
echo count($_SESSION['chart'])." ".$expected." ".$i;
//echo "<script>history.go(-1);</script>";
?>
I'm getting this output: 3 name 2.
I know that element in array exists with name 'name', but I can't unset it. Please help me.

Why not let PHP do the search?
<?php
session_start();
$key = array_search($_GET['name'], $_SESSION['chart']);
if ($key !== false) {
unset($_SESSION['chart'][$key]);
}

because you call unset out of foreach
try :
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
unset($name);
}
$i++;
}

You can make your intent clearer by using this form of foreach
foreach($_SESSION['chart'] as $idx=>$name)
{
if($name==$expected)
{
unset($_SESSION['chart'][$idx]);
break;
}
}
However, Till Helge Helwig's solution is better for this particular problem, but it's worth being aware that you don't need to maintain your own 'key' variable when using foreach.

Related

To check if an element already exists in the array and then if it does exist, delete it

The parameter is taken from the url like this file.php?item=xyz
I have an array $_SESSION['arr'].
Now I want to check if xyz is present in $_SESSION['arr'] and delete it if it is present.
In the end I send my result to the calling JQuery function as
echo json_encode($_SESSION['arr']);
EDIT: And if the element is not present, add it to the array.
Thanks in advance!
This should work for you :)
foreach ($_SESSION['arr'] as $value)
{
//converting to lowercase
$value= strtolower($value)
if($value == "xyz")
{
//removing $value from $_SESSION['arr']
unset($_SESSION['arr'][$value]);
}
else
{
//adding value to array
array_push($_SESSION['arr'], "xzy");
}
}
Use below code.
if(isset($_GET['item']) && $_GET['item'] == "xyz")
{
if(in_array($_GET['item'],$_SESSION['arr']))
{
//Delete it
}
}
if(isset($_GET['item']))
{
if(in_array($_GET['item'],$_SESSION['arr']))
{
$pos = array_search($_GET['item'], $_SESSION['arr']);
unset($_SESSION['arr'][$pos]);// deletes
}
not tested but logic like this. hope helps :)

More dynamic way of outputting Multi-Dimensional Arrays PHP

So, I am still learning PHP, and I wanted to customize the arrays a bit in matter of structure, so they are not static. But I've came to a problem. I've managed to write out each array that has an array inside of it, but now I struggle in finding a way of writing out the ones that do not have an array inside of them, and not to get 0-s and 1-s instead of the actual name of the array elements.
I basically need some advice on how to make this work properly, I wouldn't mind if you could tell me a more efficient way of writing everything out and solving the problem at the same time.
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
}
}
} else {
echo $food_types;
}
}
?>
**UPDATE***
Thanks to celeriko's comment I found the problem, being newbie to PHP I didn't really knew that the type of "Healthy Food" that was not an array was actually the first index of the big "Healthy Food" array, as the other two were array and didn't count as actual indexes.
Here is the fixed code, thank you cerleriko once again!
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
} else {
echo $fruits.'<br>'; /* Here I had to enter this line and everything works fine! */
}
}
} else {
echo $food_types;
}
}
?>
Glad you got it fixed, but as for the question "More dynamic way of outputting Multi-Dimensional Arrays", here is a recursive one. It sets a level-X class to the div that you can style:
function print_it($array) {
static $level = 1;
foreach($array as $k => $v) {
if(!is_numeric($k)) {
echo '<div class="level-'.$level.'">'.$k.'</div>'.PHP_EOL;
}
if(is_array($v)) {
$level++;
print_it($v);
$level--;
} else {
echo '<div class="level-'.$level.'">'.$v.'</div>'.PHP_EOL;
}
}
}
print_it($food);

convert array to object in php

In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Categories