October 18, 2012

Using appendTo() on the parent `ul` of $this (current) element

Question by uriah

I’m having difficulty with some syntax.

JS

function sortAlpha(a,b){
       return a.innerHTML > b.innerHTML ? 1 : -1;
};

$('.brick ul li').each(function() {
       $(this).sort(sortAlpha).appendTo('ul');
});

HTML

<div id="studio" class="brick">
<div class="listlist">
<h3 class="title">Studio</h3>
<ul class="list">
    <li class="odd">
        <a href="#">
            <span class="title">Apple</span>
        </a>
    </li>
    <li class="even">
    <span class="title"><a href="#">Cat</span>
            </a>
    </li>
    <li class="odd">
        <span class="title">
                        <a href="#">Bar</span>
        </a>
    </li>
</ul>
</div>
</div>

I would like to append $this li to it’s own parent ul not all the lists

Edit: Just to make sure I’m selecting the correct li and parent. Thanks

Answer by Sheikh Heera

You have inaccurate html, not properly nested, anyways, you may try this, I’ve answered assuming that the first li have the right nesting, as given below

<li class="odd">
    <a href="#">
        <span class="title">Apple</span>
    </a>
</li>

Working Example Here.

// Sorter
function sorter(){
    var arr=[], len=$('.brick').find('ul.list li').length;    
    $('.brick ul.list li').each(function(i) {
        var el=$(this).find('a span').text();
        arr.push(el);
        if(i==(len-1))
        {
            arr=sortAlpha(arr);
            var ul=$(this).closest('ul.list').empty();
            $.each(arr, function(k, v){
                var cls=(k%2) ? 'even':'odd',
                li=$('<li/>', {'class':cls}),
                a=$('<a/>',{'href':'#'}).append($('<span/>', {'class':'title'}).text(v));
                ul.append(li.append(a));
            });
        }
    });    
}

//Sort helper
function sortAlpha(list){
    var result = [], map = [];
    for (var i=0, length = list.length; i < length; i++) {
        map.push({ index: i, value: list[i].toLowerCase() });
    }
    map.sort(function(a, b) {
        return a.value > b.value ? 1 : -1;
    });
    for (var i=0, length = map.length; i < length; i++) {
        result.push(list[map[i].index]);
    }
    return result;
} 

Answer by Starx

If you are unsure of the parent element, then use this

$(this).sort(sortAlpha).appendTo($(this).parent("ul"));

If you are still not sure that parent is going to right above the DOM Tree then use .closest()

$(this).sort(sortAlpha).appendTo($(this).closest("ul"));

But, performance will better if you uniquely identify the ul with an id like

<ul id="meParent">
   ...
</ul>

Then

$(this).sort(sortAlpha).appendTo("#meParent");
April 27, 2012

Parse error: syntax error, unexpected T_VARIABLE in /home/rixo/public_html/login/process.php on line 41

Question by Jack-T

I am new to php. I keep having this error – Parse error: syntax error, unexpected T_VARIABLE in /home/rixo/public_html/login/process.php on line 41

Here is the full code – http://pastebin.com/8Yqmk0MX

If you could look through it for me and see what is the problem it would be a great help.

-Thank you in advance

Answer by Starx

Its due to unclosed quote on this line

$checkuser = mysql_query('SELECT username FROM user WHERE username='$user');

Fix it

$checkuser = mysql_query("SELECT username FROM user WHERE username='$user'");

Update:

Found another query error on line 61 of the paste. There is mismatching quotes

$write = “INSERT INTO user (username, password, email) VALUES ('$user', '$pwd', '$mail’)';

Fix them

$write = "INSERT INTO user (username, password, email) VALUES ('$user', '$pwd', '$mail')";
April 10, 2012

What is this PHP Syntax: ($variation_id>0) ? $variation_id : $item_id;

Question by user1325258

Is someone able to explain the meaing of the following statment, and the type of php it is reffering to so I can do further research:

$foo = ($variation_id>0) ? $variation_id : $item_id;

I have tried search but don’t really know what i’m searching for.

What I am trying to find out is the name and meaning of the following syntax
? / : and is ($variation_id>0) just a shorthand if statement ?

— I just stumbled upon conditional variables although a nice simple explanation would still be appreciated.

Answer by LAW

That is a ternary condition. If the condition on the left before the ‘?’ is true, it executes the statement after the ‘?’ and before the colon. if not, then it executes the statement after.

In english, this says “use the variation id if it is greater than zero, else use item id”

Answer by Starx

That structure is called ternary structure and in a short form of If … Else

Your Snippet:

$foo = ($variation_id>0) ? $variation_id : $item_id;

Converts to

if($variation_id>0) {
   $foo = $variation_id;
} else {
   $foo = $item_id;
}

Basically, the syntax will come down to something like this

$variable = (<CONDITION>) ? <TRUE EXPRESSION> : <FALSE EXPRESSION>;

You can also combine multiple ternary structure in one line, but it better if you use normal if, if this is over complicated.

April 6, 2012

Interpolate constant (not variable) into heredoc?

Question by Michael

<?php
   define('my_const', 100);
   echo <<<MYECHO
      <p>The value of my_const is {my_const}.</p>
MYECHO;
?>

If i put a variable inside the braces it prints out. But not the constant. How can I do it?
Thank’s!

Answer by Starx

Use sprintf()

define('my_const', 100);
$string = <<< heredoc
      <p>The value of my_const is %s.</p>
heredoc;

$string = sprintf($string, my_const);
April 4, 2012

How do I name these PHP arrays?

Question by absentx

Lets say I need three arrays, ford, chevy and dodge. Each array has three items:

$ford['engine'] = 'something';
$ford['color'] = 'something';
$ford['price'] = 'something';

$chevy['engine'] = 'something';
$chevy['color'] = 'something';
$chevy['price'] = 'something';

$dodge['engine'] = 'something';
$dodge['color'] = 'something';
$dodge['price'] = 'something';

I can write that out no problem and it doesn’t take too long. But, lets say I need fifty or sixty arrays that I need to make, all with ten to twenty different items. I want to put a variable at the top of each array’s file to denote what the array name will be, but I am not quite clear on the syntax and I am not too familiar with $$ or how I would use that with arrays:

$name = 'ford';

$(I want this to be "$name")['engine'] = 'something';
$(I want this to be "$name")['color'] = 'something';
$(I want this to be "$name")['price'] = 'something';

I have also considered just doing this:

$name = 'ford';

$view[$name.'_engine'] 
$view[$name.'_color'] 
$view[$name.'_price'] 

Can I get some suggestions on the best way to approach this?

Answer by Starx

Write a small function to do that

$cars = array(); //Create an array to hold the values    
function writeArray($car, $var1, $var2, $var3) {
     global $cars;
     $cars[$car] = array('engine' =>  $var1, 'color' => $var2, 'price' => $var2);
}
//Now use it like
writeArray('Chevy', $something, $something, $something);

//If you want to access the array in the form of $ford['engine'] then use this

extract($cars); //This will split the array into small array accessible by model 
March 8, 2012

wrapping a function as a jQuery parameter

Question by Joseph the Dreamer

i am buliding an autocomplete for my website when i came across this style of building code:

$(function() {

    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $(element).autocomplete(....

    //more code
});

i know about closures, “IIFE”s but this one’s a new one for me.

  • what’s with the “jQuery-wrapped” code above?
  • is there any particular reason i should do that? (scope?)
  • optimization-wise, should i even do it that way?

Answer by Starx

  1. $(function() { }); is equivalent to $(document).ready(function() {}); and as before it executes once the DOM has been ready.

  2. Defining a function inside is to tell that, the function is only available once the dom is ready to execute.

  3. $(element).autocomplete(.... is simply implementing the plugin to the selector, once the DOM is ready to execute.

Hope its clear now 🙂


$(function() { or $(document).ready(function() { does not need the whole page to load, to run as $(window).load(fn) does.

February 27, 2012

One line code to get one value from function that returns an array

Question by Salman A

Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)

In PHP there are functions that return an array, for example:

$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com

My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:

echo parse_url("http://stackoverflow.com/q/9461027/87015")["host"];

Answer by Starx

You can do a little trick instead, write a simple function

function readArr($array, $index) {
    return $array[$index];
}

Then use it like this

echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
September 26, 2011

Are there any essential reasons to use isset() over @ in php

Question by Tchalvak

So I’m working on cleanup of a horrible codebase, and I’m slowly moving to full error reporting.

It’s an arduous process, with hundreds of notices along the lines of:

Notice: Undefined index: incoming in /path/to/code/somescript.php on line 18

due to uses of variables assuming undefined variables will just process as false, like:

if($_SESSION['incoming']){
    // do something
}

The goal is to be able to know when a incorrectly undefined variable introduced, the ability to use strict error/notice checking, as the first stage in a refactoring process that -will- eventually include rewriting of the spots of code that rely on standard input arrays in this way. There are two ways that I know of to replace a variable that may or may not be defined
in a way that suppresses notices if it isn’t yet defined.

It is rather clean to just replace instances of a variable like $_REQUEST['incoming'] that are only looking for truthy values with

@$_REQUEST['incoming'].

It is quite dirty to replace instances of a variable like $_REQUEST['incoming'] with the “standard” test, which is

(isset($_REQUEST['incoming'])? $_REQUEST['incoming'] : null)

And you’re adding a ternary/inline if, which is problematic because you can actually nest parens differently in complex code and totaly change the behavior.

So…. …is there any unacceptable aspect to use of the @ error suppression symbol compared to using (isset($something)? $something : null) ?

Edit: To be as clear as possible, I’m not comparing “rewriting the code to be good” to “@”, that’s a stage later in this process due to the added complexity of real refactoring. I’m only comparing the two ways (there may be others) that I know of to replace $undefined_variable with a non-notice-throwing version, for now.

Answer by user187291

Another option, which seems to work well with lame code that uses “superglobals” all over the place, is to wrap the globals in dedicated array objects, with more or less sensible [] behaviour:

class _myArray implements ArrayAccess, Countable, IteratorAggregate
{
     function __construct($a) {
       $this->a = $a;
     }

    // do your SPL homework here: offsetExists, offsetSet etc

    function offsetGet($k) { 
        return isset($this->a[$k]) ? $this->a[$k] : null;
        // and maybe log it or whatever
    }
}

and then

 $_REQUEST = new _myArray($_REQUEST);

This way you get back control over “$REQUEST” and friends, and can watch how the rest of code uses them.

Answer by Starx

You answered you question yourself. It suppress error, does not debug it.

August 17, 2011

Making an option in an HTML dropdown menu selected.

Question by Mason240

Thanks for reading my question.

I have a website that uses PHP for a searchable card database. Right now I have the code for the head/searchbox section on each page, but I want to use functions instead. The function itself is working. The problem is with the drop down boxes. I currently have it set up so that when a user selects and option, and then searches, the selections are selected on the next page.

I am sure that I am having a problem with syntax.

Here is an example of the working code, which is used on the live site right now.

    <select name="Type" onchange="this.submit()">
        <option value="1" >[All Card Types] </option>
        <option value="Hero" <?php if($_GET['Type'] == "Hero") echo "selected='selected'"; ?>> Hero </option>
        <option value="Ally" <?php if($_GET['Type'] == "Ally") echo "selected='selected'"; ?>> Ally </option>
    </select>

This is the relevant code from the function, which is not working, and is on the test site (ignore the error):

function searchBox(){
//Cell 1
    echo '
        <select name="Type" onchange="this.submit()">
            <option value="1" >[All Card Types] </option>
            <option value="Hero"  <?php if($_GET["Type"] == "Hero") { echo "selected=selected" ; }?>>   Hero    </option>
            <option value="Event" <?php if($_GET["Type"] == "Event") { echo "selected=selected"; }?>>   Event </option>
        </select>
    ';
}

As you can see in the test page, the dropdown menu doesn’t function like it does on the live page.

Thanks for the help!

Answer by Jonah

You can’t embed <?php tags in a string like that. You have to concatenate it with ternary operators.

function searchBox(){
//Cell 1
    echo '
        <select name="Type" onchange="this.submit()">
            <option value="1" >[All Card Types] </option>
            <option value="Hero"' . ($_GET['Type'] == 'Hero' ? ' selected=""' : '') . '>   Hero    </option>
            <option value="Event"' . ($_GET['Type'] == 'Event' ? ' selected=""' : '') . '>   Event </option>
        </select>
    ';
}

But for the sake of maintainability, you might do something more like this:

function searchBox() {
    $types = array('Hero', 'Event');
    $output = '<select name="Type" onchange="this.submit()">';
    $output .= ' <option value="1" >[All Card Types] </option>';
    foreach ($types as $type) {
        $output .= '<option value="' . $type . '"' . ($_GET['Type'] == $type ? ' selected=""' : '') . '>    ' . $type . '    </option>';
    }
    $output .= '</select>';
    echo $output;
}

Answer by Starx

You are missing the quotes

echo "selected="selected""
November 26, 2010

jQuery question regarding if statement and position moving

Question by alexcu

I’m trying to write a program where basically the user clicks on an image and the image will then move to the right by 25px. The image moves when I click on it, but I tried to add a piece of code which makes the image return to the left of the window when it passes the right side of the window. I’ve tried using an If statement in the animation’s procedure but it doesn’t seem to work. Here’s what I have:

$('#image').click(function() {
$(this).animate({
   left: '+=155',
function() {
    if ($(this).left > $(document).width)  {
 $(this).left = 0
  }
   };

    });

});


Am I using the wrong syntax or is my function wrong? Thanks for your help.

Answer by Starx

Where is your duration?

Try this,

$('#image').click(function() {
     $(this).animate(
            {
               left: '+=155'
            },
            5000,
            function() {
                if ($(this).left > $(document).width)  {
                $(this).left = 0
                }    
       );
});
...

Please fill the form - I will response as fast as I can!